本文介绍了如何保存和读取 NSObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个 NSObject.

I have two NSObject's.

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

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

基本上对象 Car 有一个 NSSet 汽车,NSSet 汽车的每个对象都有属性图片和名称.

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

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

推荐答案

为了便于添加或删除,您的cars"属性应声明为 NSMutableSet.

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

假设你的单个 Car 对象被命名为listOfCars",这里有一种方法来做(我认为)你正在尝试做的事情:

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];
}

并且,在您的 Car .m 文件中,执行以下操作:

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

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

init 方法是唯一您应该引用cars"属性的基础变量的地方.如果您指的是从 Car 对象中设置的汽车,则其他任何地方都应该是listOfCars.cars"或self.cars".

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.

这篇关于如何保存和读取 NSObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 04:36