如何使用UIPICKERVIEW在实体之间管理数据? [英] How to manage data between the entities with the UIPICKERVIEW?

查看:114
本文介绍了如何使用UIPICKERVIEW在实体之间管理数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本库存应用程序中有一个方案。



我从核心数据实体获取记录,并希望针对该记录输入其他记录。 p>

我有两个核心数据实体类别和产品



我已经建立了他们的关系。

$



现在我想根据所选类别添加产品。



因为我使用 UIPICKERVIEW 来显示类别名称。



我目前显示 UIPICKERVIEW



的名称当用户选择名称并输入记录 id 应存储在关系字段为的产品实体中。



目前,UIPICKERVIEW从类别表



中显示类别的名称,其中它们是将数据插入到针对该类别的Product表中的表单。



在简单中,我想在选择器中显示名称,在后端中,将针对该名称存储id。



  @property(nonatomic,retain)NSString * name; 
@property(nonatomic,retain)NSNumber * is_active;
@property(nonatomic,retain)NSString * descript;
@property(nonatomic,retain)NSSet * products;

IN Product.h我有

  @property(nonatomic,retain)NSString * name; 
@property(nonatomic,retain)NSNumber * is_active;
@property(nonatomic,retain)NSString * descript;
@property(nonatomic,retain)Category * category;

IMSAddProductViewController.h

  #import< UIKit / UIKit.h> 
#importIMSAppDelegate.h

@interface IMSAddProductViewController:UIViewController< UITextFieldDelegate,UIPickerViewDataSource,UIPickerViewDelegate>

@property(weak,nonatomic)IBOutlet UIPickerView * categoryPicker;
@property(weak,nonatomic)IBOutlet UITextField * txtEnterName;
@property(weak,nonatomic)IBOutlet UITextField * txtEnterDescription;
@property(weak,nonatomic)IBOutlet UISwitch * txtIsActive;
@property(weak,nonatomic)IBOutlet UILabel * lblValuePicker;

@property(nonatomic,retain)NSArray * arr;
@property(assign,nonatomic)NSMutableArray * categoryArray;

- (IBAction)btnSave:(id)sender;



@end

实体1类别



IMSAddProductViewController.m //(UIViewController子类)

  #importIMSAddProductViewController.h
#importIMSAppDelegate.h
#importProduct.h
#importCategory.h

@interface IMSAddProductViewController()
{

NSManagedObjectContext * context;

}
@end

@implementation IMSAddProductViewController
@synthesize arr;
@synthesize txtIsActive;
@synthesize categoryArray;
@synthesize txtEnterName;
@synthesize txtEnterDescription;
@synthesize categoryPicker;
@synthesize lblValuePicker;



- (void)viewDidLoad
{
[super viewDidLoad];

self.categoryPicker.delegate = self;


IMSAppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
context = [appDelegate managedObjectContext];

NSEntityDescription * category = [NSEntityDescription entityForName:@CategoryinManagedObjectContext:context];

NSFetchRequest * request = [[NSFetchRequest alloc] init];

request.resultType = NSDictionaryResultType;

[request setEntity:category];

NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc]

initWithKey:@nameascending:YES];

[request setSortDescriptors:@ [sortDescriptor]];

// request.propertiesToFetch = [NSArray arrayWithObject:[[category propertiesByName] objectForKey:@name]];

request.returnsDistinctResults = YES;

request.resultType = NSDictionaryResultType;


NSError * error;

NSArray * array = [context executeFetchRequest:request error:& error];

// NSMutableArray * results = [[context executeFetchRequest:request error:& error] mutableCopy];

if(array == nil){

//错误句柄在这里
}
NSArray * results2 = [array valueForKeyPath:@name ];

[self setArr:results2];

// [self setArr:results];

NSLog(@name:%@,self.arr);



}

// - (void)addProducts:(NSSet *)values {
//
/ /}



- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
// return _countryNames.count;
return self.arr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
titleForRow:(NSInteger)row
forComponent:(NSInteger)component
{
// return _countryNames [row];
return self.arr [row];
}




- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
inComponent:(NSInteger )component
{
categoryArray = [self.arr objectAtIndex:row];
NSLog(@name:%@,self.categoryArray);
//这两个都返回类别的名称。
self.categoryPicker = [self.arr objectAtIndex:row];
NSLog(@name:%@,self.categoryPicker);

NSLog(@id:%d,row);


}

我将资料插入PRODUCT

   - (IBAction)btnSave:(id)sender {

NSEntityDescription * entityDesc = [NSEntityDescription entityForName:@ProductinManagedObjectContext:context];

NSManagedObject * newProduct = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];

[newProduct setValue:self.txtEnterName.text forKey:@name];

[newProduct setValue:self.txtEnterDescription.text forKey:@descript];

if(self.txtIsActive.isOn){

[newProduct setValue:@(self.txtIsActive.isOn)forKey:@is_active];
}

else {

[newProduct setValue:@(self.txtIsActive.tag =='0')forKey:@is_active];

}



//在这个代码块中应该做什么
/ *
lblValuePicker.text = [NSString stringWithFormat:@%d,[self.categoryPicker selectedRowInComponent:0]];
NSLog(@row number:%@,lblValuePicker.text);
[newProduct setValue:lblValuePicker.text forKey:@category];
* /


NSError * error = nil;

if(![context save:& error]){

//处理错误

NSLog(@some error) ;
}
else
{
NSLog(@dataentered);
}

}

这是我的快感FROM BASE





其核心数据自己管理我没有创建任何ID或主键的索引。

解决方案

1。
我建议您阅读此官方文档:如何创建,初始化和保存托管对象



2。
理解何时在选择器视图中选择行,然后调用以下委托,在其中我可以看到你使用了一个数组。这是错误的:

   - (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row 
inComponent :(NSInteger)component
{
categoryArray = [self.arr objectAtIndex:row];
}

从所选行中,您将只获得类别的名称,是在数组中。我想你必须在这里得到一个错误,因为你是一个 NSString 到数组。
要正确地做,我建议你更改以前的代码,以及。相反,从Core Data中只提取Category实体的name属性,你可以获取整个Category实体。



我可以在这里给你代码,但不会对你有任何好处。



获取整个类别实体,对'name'使用排序desciptor,否则可能会在稍后创建问题,并在 UIPickerView



3。
更改您的 didSelectRow 实现。 Donot把任何东西放在数组中。

创建类型为类别的实例变量,并使用 objectAtIndex 方法,获取相应的类别并将其放在您的实例变量中。



4。
btnSave 方法中,使用实例变量将您的产品映射到selectedCategory。请通过上面提到的链接,了解如何创建,初始化和保存托管对象,因为我可以看到你使用了大量的键值编码,虽然没有错,但不是很大程度上遵循的政策。 p>

I have a scenario in my basic inventory app.

i fetched the records from the core data entity and want other records to be entered against that one.

I have two core data entities Category and Product

i have made their relationship as well.

i have done with the category part.

now i want to add Products against the selected category.

for that i am using a UIPICKERVIEW to show the category name.

I am currently showing the names to the UIPICKERVIEW

When the user select the name and enter records the id should be stored in the Product entity where the relational field is.

Currently the UIPICKERVIEW is showing the name of the category from the Category table

where their is a form to insert the data to the Product table against that category.

In Simple i want to show names in the picker and in backend the id will be stored against that name.

In Category.h entity i have

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * is_active;
@property (nonatomic, retain) NSString * descript;
@property (nonatomic, retain) NSSet *products;

IN Product.h I have

@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) NSNumber * is_active;
@property (nonatomic, retain) NSString * descript;
@property (nonatomic, retain) Category *category;

IMSAddProductViewController.h

#import <UIKit/UIKit.h>
#import "IMSAppDelegate.h"

@interface IMSAddProductViewController : UIViewController < UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate>

@property (weak, nonatomic) IBOutlet UIPickerView *categoryPicker;
@property (weak, nonatomic) IBOutlet UITextField *txtEnterName;
@property (weak, nonatomic) IBOutlet UITextField *txtEnterDescription;
@property (weak, nonatomic) IBOutlet UISwitch *txtIsActive;
@property (weak, nonatomic) IBOutlet UILabel *lblValuePicker;

@property(nonatomic,retain)NSArray *arr;
@property (assign, nonatomic) NSMutableArray *categoryArray;

- (IBAction)btnSave:(id)sender;



@end

Getting results From Entity 1 Category

IMSAddProductViewController.m //(UIViewController sub class)

#import "IMSAddProductViewController.h"
#import "IMSAppDelegate.h"
#import "Product.h"
#import "Category.h"

@interface IMSAddProductViewController ()
{

    NSManagedObjectContext *context;

}
@end

@implementation IMSAddProductViewController
@synthesize arr;
@synthesize txtIsActive;
@synthesize categoryArray;
@synthesize txtEnterName;
@synthesize txtEnterDescription;
@synthesize categoryPicker;
@synthesize lblValuePicker;



  - (void)viewDidLoad
{
    [super viewDidLoad];

    self.categoryPicker.delegate = self;


    IMSAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
    context = [appDelegate managedObjectContext];

    NSEntityDescription *category = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:context];

    NSFetchRequest *request = [[NSFetchRequest alloc ] init];

    request.resultType = NSDictionaryResultType;

    [request setEntity:category];

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]

                                        initWithKey:@"name" ascending:YES];

    [request setSortDescriptors:@[sortDescriptor]];

//    request.propertiesToFetch = [NSArray arrayWithObject:[[category propertiesByName] objectForKey:@"name"]];

    request.returnsDistinctResults = YES;

    request.resultType = NSDictionaryResultType;


    NSError *error;

    NSArray *array = [context executeFetchRequest:request error:&error];

   // NSMutableArray *results = [[context executeFetchRequest:request error:&error] mutableCopy];

    if (array == nil) {

        //error handle here
    }
    NSArray* results2 = [array valueForKeyPath:@"name"];

    [self setArr:results2];

    // [self setArr:results];

    NSLog (@"name: %@",self.arr);



}

//-(void) addProducts:(NSSet *)values {
//     
//}



- (NSInteger)numberOfComponentsInPickerView:
(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView
numberOfRowsInComponent:(NSInteger)component
{
   // return _countryNames.count;
    return self.arr.count;
}

- (NSString *)pickerView:(UIPickerView *)pickerView
             titleForRow:(NSInteger)row
            forComponent:(NSInteger)component
{
    //return _countryNames[row];
    return self.arr[row];
}




   -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
    categoryArray = [self.arr objectAtIndex:row];
    NSLog (@"name: %@",self.categoryArray );
    // both of these are returning the name of categories.
    self.categoryPicker = [self.arr objectAtIndex:row];
    NSLog (@"name: %@",self.categoryPicker);

    NSLog(@"id : %d", row);


}

THE CODE WHERE I AM INSERTING DATA TO PRODUCT

  - (IBAction)btnSave:(id)sender {

    NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"Product" inManagedObjectContext:context];

    NSManagedObject *newProduct = [[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:context];

    [newProduct setValue:self.txtEnterName.text forKey:@"name"];

    [newProduct setValue:self.txtEnterDescription.text forKey:@"descript"];

    if (self.txtIsActive.isOn) {

        [newProduct setValue: @(self.txtIsActive.isOn) forKey:@"is_active"];
    }

    else{

        [newProduct setValue: @(self.txtIsActive.tag == '0') forKey:@"is_active"];

    }



    // what should be done in this block of code
    /*
    lblValuePicker.text = [NSString stringWithFormat:@"%d",[self.categoryPicker selectedRowInComponent:0]];
    NSLog(@"row number: %@", lblValuePicker.text);
    [newProduct setValue:lblValuePicker.text forKey:@"category"];
    */


    NSError *error = nil;

    if (![context save:&error]) {

        //handle the error

        NSLog(@"some error");
    }
    else
    {
        NSLog(@"dataentered");
    }

}

HERE IS THE SNAPSHOT I HAVE IT FROM BASE

THE CORE DATA IT SELF MANAGES THE INDEXES I HAVEN'T CREATE ANY ID OR PRIMARY KEY FOR THAT.

解决方案

1. I would suggest you read this Official documentation on How to create, initialize and save a Managed Object.

2. Understand when you select the row in picker view then the below delegate is called, in which I can see you have used an array. This is wrong:

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
      inComponent:(NSInteger)component
{
    categoryArray = [self.arr objectAtIndex:row];
}

From the selected row, you would get only the name of the Category because that is in the array. I guess you must be getting an error here, because you are equilating an NSString to an array. To do it correctly I would suggest you to change the previous code as well. Instead, of fetching only name property from Category entity from Core Data, you fetch the whole Category entities.

I can give you code here but that wont be any good for you. You must try first.

Fetch the whole Category Entity, use a sort desciptor for 'name'- otherwise it may create problem later and in UIPickerView- titleForRow delegate method, use dot(.) operator to display name.

3. Change your didSelectRow implementation. Donot put anything in the array. You need the selected Category to map against the newly created Product.
Create an instance variable of type Category, and using objectAtIndex method, get the corresponding Category and put it inside your instance variable.

4. In btnSave method, use the instance variable to map your Product against the selectedCategory. Please go through he link mentioned above to understand how to create, initialize and save the managed object, because I can see you are using a lot of key- value coding which is though not wrong, but is not the largely followed policy.

这篇关于如何使用UIPICKERVIEW在实体之间管理数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆