访问ios中@property的setMethod

时间:2015-08-03 13:24:24

标签: ios objective-c

经过数小时的教程和谷歌搜索后,我知道当我们在头文件中定义一个属性时,编译器会自动生成setter和getter这里是一个例子:
" example.h文件"

@property(strong,nonatomic) NSNumber *test;

example.m

[self.test setTest [@"3"]];

所以我想要的是访问此方法来检查方法声明,这就是我想要的原因

完整情景

@interface exampleController ()  
{

    int example;
}

//这是一个用于保存值的实例变量,当运行的应用程序从字典中获取此值,然后将示例变量的值保存到核心数据

这是实体类

exampleEntity.h

 @property(strong,nonatomic) NSNumber *example;

exampleEntity.m

@dynamic example;

//由于实例变量是int,我们需要将它强制转换为NSNumber,所以我遵循这个link

[entry setExample : [NSNumber numberWithInt:example]];
运行此代码后

最后我将进入此异常:

  

***由于未捕获的异常终止应用程序' NSInvalidArgumentException'

完整代码

    #import "viewController.h"
    @interface viewController ()  
   {

         int example;
    }


- (void)viewDidLoad {
gettingTheExampleValueFromDictionary();
}



-(void)gettingTheExampleValueFromDictionary()


 {

                NSDictionary *dictionary = [NSJSONSerialization    JSONObjectWithData:requestHandler options:0 error:&jsonParsingError];
       example = [[dictionary objectForKey:@"exampleId"] intValue];


 }



- (IBAction)doneButton:(id)sender {

  [self insertDataToCoreData];
  [self dismissSelf];
}

      -(void)insertDataToCoreData   {

   CoreData *coreDataStack = [CoreData defaultStack];
        ExampleEntity *entry = [NSEntityDescription insertNewObjectForEntityForName:
                                    @"ExampleEntity" inManagedObjectContext:coreDataStack.managedObjectContext];

            [entry setExample :[NSNumber numberWithInt:example]];
// here we go into the error //



    [coreDataStack saveContext];
    }





  @end
// and if you ask me for entity class here is:

 #import <Foundation/Foundation.h>
 @interface ReservationEntity : NSObject
 @property (nonatomic,strong) NSNumber *example;
   @end



 #import "exampleEntity.h"
 @implementation exampleEntity
 @dynamic example;
 @end
 // and if you ask me for core data here is the pic needed //

core data

   // the configuration of xcdatamodel

configuration of xcdatamodel

1 个答案:

答案 0 :(得分:2)

在您的情况下,您应该更改:

@dynamic example;

@synthesize example;

或者只删除代码行@dynamic示例。

因为@synthesize为属性生成getter&amp; setter,而@dynamic意味着getter&amp; setter是在运行时创建的(例如NSManagedObject的子类)