如何在另一个类中正确使用@property(Setters)

时间:2014-01-15 12:18:58

标签: objective-c properties setter

另一个问题我正在尝试在另一个类中使用setter但我似乎在这里得到这个奇怪的错误是下面的代码:

AppDataSorting.h

    #import <Foundation/Foundation.h>

    @interface AppDataSorting : NSObject{
        NSString *createNewFood;
        NSNumber *createNewFoodCarbCount;
    }

    @property (readwrite) NSString *createNewFood;

    @end

AppDelegate.m

    #import "AppDelegate.h"

    @implementation AppDelegate

    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification
    {
        // Insert code here to initialize your application
    }

    - (IBAction)saveData:(id)sender {
        NSLog(@"%@", self.foodName.stringValue);
        self.createNewFood = self.foodName.stringValue;
        NSLog(@"%.1f", self.carbAmount.floatValue);
    }
    @end

我在AppDelegate.m中收到错误消息:在'AppDelegate *'类型的对象上找不到属性'createNewFood'

有人可以在这里解释一下这个问题吗?

3 个答案:

答案 0 :(得分:2)

您声明此属性:

@property (readwrite) NSString *createNewFood;

在AppDataSorting.h中,您可以像AppDataSorting.m文件中的self.createNewFood一样访问它,而不是AppDelegate.m。如果你想像在AppDelegate.m中那样调用它,你可以移动这一行:

@property (readwrite) NSString *createNewFood;

到AppDelegate.h文件。

或者如果你想在AppDelegate中使用AppDataSorting类的属性,你必须创建对象并在该对象上调用它:

- (IBAction)saveData:(id)sender {
        NSLog(@"%@", self.foodName.stringValue);
        AppDataSorting *dSorting = [[AppDataSorting alloc] init];
        dSorting.createNewFood = self.foodName.stringValue;
        NSLog(@"%.1f", self.carbAmount.floatValue);
    }

答案 1 :(得分:0)

-saveData:中,self指的是NSAppDelegate的一个实例。 createNewFood属性是在类AppDataSorting的实例上定义的。

另请注意,Cocoa / CF命名约定对以“init”,“new”和(在较小程度上)“create”开头的方法赋予特殊含义。您可能希望在您的属性名称中避免此类内容。 Details here

通常,属性应表示对象的概念“属性”。因此,如果您有一个Person类,它可能具有name属性,但它没有createNewOutfit属性。

答案 2 :(得分:0)

您需要在createNewFood的实例上访问AppDataSorting - 但您正在尝试访问AppDelegate类上的属性,而该属性显然没有实现它。 因此,您需要创建一个AppDataSorting实例,然后像这样访问该属性:

AppDataSorting *instance = [[AppDataSorting alloc] init];
instance.createNewFood = self.foodName.stringValue;

最后的说明:

  • docs提供了良好的信息基础
  • 如果您不需要原子性,则应始终使用非原子属性声明属性
  • createNewFood不是一个好名字,因为它建议一种创造新食物的方法 - 但它只是为了存储数据(在这种情况下是一个NSString实例)
相关问题