NSString未指定“分配",“保留"或“复制"属性 [英] NSString no 'assign', 'retain', or 'copy' attribute is specified

查看:85
本文介绍了NSString未指定“分配",“保留"或“复制"属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在类中声明了NSString属性,而Objective-c则在抱怨:

I'm declaring an NSString property in a class and objective-c is complaining that:

NSString未指定分配",保留"或复制"属性
NSString no 'assign', 'retain', or 'copy' attribute is specified

然后随便让我知道改为使用分配".

It then casually lets me know that "assign is used instead".

有人可以向我解释分配保留复制在正常C内存管理方面的区别 >功能?

Can someone explain to me the difference between assign, retain and copy in terms of normal C memory management functions?

推荐答案

我想引起您注意使用assign而不是retaincopy的事实.由于NSString是对象,因此在引用计数的环境(即,没有垃圾回收)中,这可能是危险的"(除非是有意设计的).

I think it is drawing your attention to the fact that a assign is being used, as opposed to retain or copy. Since an NSString is an object, in a reference-counted environment (ie without Garbage Collection) this can be potentially "dangerous" (unless it is intentional by design).

但是,assignretaincopy之间的区别如下:

However, the difference between assign, retain and copy are as follows:

  • 分配:在属性的设置方法中,可以简单地将实例变量分配给新值,例如:

  • assign: In your setter method for the property, there is a simple assignment of your instance variable to the new value, eg:

- (void)setString:(NSString*)newString
{
    string = newString;
}

这可能会导致问题,因为Objective-C对象使用引用计数,因此如果不保留对象,则有可能在您仍在使用字符串时将其释放.

This can cause problems since Objective-C objects use reference counting, and therefore by not retaining the object, there is a chance that the string could be deallocated whilst you are still using it.

保留:此保留 setter方法中的新值.例如:

retain: this retains the new value in your setter method. For example:

- (void)setString:(NSString*)newString
{
    [newString retain];
    [string release];
    string = newString;
}

这是更安全的方法,因为您明确声明要维护该对象的引用,并且必须在释放该对象之前释放它.

This is safer, since you explicitly state that you want to maintain a reference of the object, and you must release it before it will be deallocated.

复制:这会在您的setter方法中复制字符串:

copy: this makes a copy of the string in your setter method:

- (void)setString:(NSString*)newString
{
    if(string!=newString)
    {
        [string release];
        string = [newString copy];
    }
}

这通常与字符串一起使用,因为制作原始对象的副本可确保在您使用它时不会对其进行更改.

This is often used with strings, since making a copy of the original object ensures that it is not changed whilst you are using it.

这篇关于NSString未指定“分配",“保留"或“复制"属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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