原始数据类型的Objective-C属性

时间:2022-04-17 12:57:33

Having something like this

有这样的事情

@interface MyClass : UIImageView {
   BOOL autoResize;
}
@property BOOL autoResize;
@end

I create an array of objects like this:

我创建了一个像这样的对象数组:

MyClass* o1 = [[MyClass alloc] init];
o1.autoResize = true;
[myArray addObject:o1];

MyClass* o2 = [[MyClass alloc] init];
o2.autoResize = false
[myArray addObject:o2];

The problem is the following: if I now use an iterator to iterate through all objects, myObject.autoResize allways(!) returns false. E.g:

问题如下:如果我现在使用迭代器遍历所有对象,myObject.autoResize allways(!)将返回false。例如:

for (MyClass elem in myArray) {
    elem.autoResize ? NSLog(@"true") : NSLog(@"false");
}

would echo "false", "false". I guess I have a vague why this happens (because BOOL is a primitive data type and not an object). But what is the best practice to deal with this issue?

会回应“假”,“假”。我想我有一个含糊不清的原因(因为BOOL是原始数据类型而不是对象)。但是处理这个问题的最佳做法是什么?

Thanks

谢谢

Christian

基督教

2 个解决方案

#1


1  

Try to add (nonatomic, assign) property modifiers

尝试添加(非原子,赋值)属性修饰符

@property (nonatomic, assign) BOOL autoResize;

How it work you can read here: Declared Properties

它是如何工作的你可以在这里阅读:声明的属性

#2


0  

Sorry folks! That was a perfect example of why you should revisit your code before posting it here... Actually, what I did was:

对不起人!这是一个完美的例子,说明为什么你应该在发布之前重新访问你的代码......实际上,我所做的是:

MyClass* o1 = [[MyClass alloc] init];
o1.autoResize = true;
[myArray addObject:o1];

myArray = [[NSMutableArray alloc] init];  // OMG! What is this doing here :-(

MyClass* o2 = [[MyClass alloc] init];
o2.autoResize = false
[myArray addObject:o2];

As I had dozends of objects I simply overlooked this line... Thanks @Carl Veazey for the hint.

由于我对物体的影响,我只是忽略了这一行......感谢@Carl Veazey的暗示。

bye Christian

再见基督徒

#1


1  

Try to add (nonatomic, assign) property modifiers

尝试添加(非原子,赋值)属性修饰符

@property (nonatomic, assign) BOOL autoResize;

How it work you can read here: Declared Properties

它是如何工作的你可以在这里阅读:声明的属性

#2


0  

Sorry folks! That was a perfect example of why you should revisit your code before posting it here... Actually, what I did was:

对不起人!这是一个完美的例子,说明为什么你应该在发布之前重新访问你的代码......实际上,我所做的是:

MyClass* o1 = [[MyClass alloc] init];
o1.autoResize = true;
[myArray addObject:o1];

myArray = [[NSMutableArray alloc] init];  // OMG! What is this doing here :-(

MyClass* o2 = [[MyClass alloc] init];
o2.autoResize = false
[myArray addObject:o2];

As I had dozends of objects I simply overlooked this line... Thanks @Carl Veazey for the hint.

由于我对物体的影响,我只是忽略了这一行......感谢@Carl Veazey的暗示。

bye Christian

再见基督徒