简体   繁体   English

如何保存和读取NSObject

[英]How to save to and read from a NSObject

I have two NSObject's. 我有两个NSObject。

@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. 基本上,对象Car具有一个NSSet汽车,并且NSSet汽车中的每个对象都具有属性图片和名称。

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. 如何关联这两个NSObject,以及如何使用Model NSObject的属性将字符串或图像保存到Car NSSet。 Thanks. 谢谢。

For easy adding or removing, your " cars " property should be declared as a NSMutableSet . 为了方便添加或删除,应将您的“ cars ”属性声明为NSMutableSet

And assuming your single Car object is named " listOfCars ", here is one way to do what (I think) you are trying to do: 并假设您的单个Car对象被命名为“ listOfCars ”,这是一种(我认为)您尝试做的事情:

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: 并且,在您的Car .m文件中,执行以下操作:

- (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. init方法是您应引用“ cars ”属性的基础变量的唯一位置。 Everywhere else it should be " listOfCars.cars " or " self.cars " if you're referring to the cars set from within the Car object. 如果要引用从Car对象内部设置的汽车,则其他任何地方都应该是“ listOfCars.cars ”或“ self.cars ”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM