objective-c:属性不允许的双指针? [英] objective-c: double pointers to property not allowed?

查看:374
本文介绍了objective-c:属性不允许的双指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个这样的方法:

I want to create a method like this:

- (void) checkAndUpdateStringProperty: (NSString **) property{
   if (...) 
      *property = @"whatever";
}



我想使用它来传递同一个类的属性: / p>

I want to use this to pass in a property for the same class:

- (void) somewhereElse{
       ....
       [self checkAndUpdateStringProperty: &self.productName];
}

但是这会产生语法错误,说请求的属性表达式的地址。任何原因为什么?如果我用一个局部变量替换类的属性,它工作正常:

But this gives a syntax error, saying "Address of property expression requested". Any reason why? If I replace the class property with a local variable, it works fine:

- (void) somewhereElse{
       NSString *name = nil;
       [self checkAndUpdateStringProperty: &name];
}


推荐答案

通过其getter和setter方法,除了在对象的 init dealloc 方法中初始化和取消初始化它们对象不处于完全一致的状态) - 访问它们任何其他方式违背其目的并且不尊重它们的属性( retain copy 等)。

Properties should only ever be accessed through their getter and setter methods, with the exception of initializing and deinitializing them in the object's init and dealloc methods (when the object is not in a fully consistent state) -- accessing them any other way defeats their purpose and does not respect their attributes (retain, copy, etc.).

它不编译的原因是因为属性访问器是方法调用的语法糖,取一个方法的返回值的地址。 self.productName [self productName] & [self productName] 没有意义。

The reason why it doesn't compile is because property accessors are syntactic sugar for method calls, and you can't take the address of the return value of a method. self.productName is identical to [self productName], and &[self productName] makes no sense.

如果你真的想这样做,不要使用属性,只使用一个常规变量(如局部变量或ivar)和记录函数的语义:调用函数需要 release 返回的对象吗?等等。例如,采用 NSError ** 的各种Apple方法指定返回的错误对象(如果有的话)是自动释放的对象,因此您不应发布,除非您也保留

If you really want to do this, don't do it with a property, do it with just a regular variable (such as a local variable or ivar), and document the semantics of your function: does the calling function need to release the returned object? Etc. For example, the various Apple methods which take an NSError** specify that the error object which is returned, if any, is an autoreleased object, so you should not release it yourself unless you also retain it.

这篇关于objective-c:属性不允许的双指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆