How to save to and read from a NSObject

佐手、 提交于 2019-12-12 10:23:05

问题


I have two NSObject's.

@interface Car : NSObject{
     @property (strong) NSSet *cars;
}

and

@interface Model : NSObject{
     @property (strong) UIImage *picture;
     @property (strong) NSString *name;
}

Basically the object Car has a NSSet cars and each object of the NSSet cars has the properties picture and name.

How can I relate this two NSObject's and how can I save a string or image to the Car NSSet using the properties of the Model NSObject. Thanks.


回答1:


For easy adding or removing, your "cars" property should be declared as a NSMutableSet.

And assuming your single Car object is named "listOfCars", here is one way to do what (I think) you are trying to do:

Model * newModel = [[Model alloc] init];
if(newModel)
{
    newModel.picture = [UIImage imageNamed: @"Edsel.jpg"];
    newModel.name = @"Ugly Car";

    [listOfCars.cars addObject: newModel];
}

And, in your Car .m file, do something like this:

- (id) init
{
    self = [super init];
    if(self)
    {
        _cars = [[NSMutableSet alloc] init];
    }
    return(self);
}

The init method is the only place you should be referring to the underlying variable for your "cars" property. Everywhere else it should be "listOfCars.cars" or "self.cars" if you're referring to the cars set from within the Car object.



来源:https://stackoverflow.com/questions/17244823/how-to-save-to-and-read-from-a-nsobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!