哪种方式是正确的方式分配内存与属性? [英] Which way is the correct way to allocate memory with a property?

查看:108
本文介绍了哪种方式是正确的方式分配内存与属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪种方式是正确的?

  NSString * c = [[NSString alloc] init]; 
self.character = c;
[c release];

  self.character = [[NSString alloc] init]; 

为什么?感谢。

解决方案

这取决于您的属性如何声明。如果你使用

  @property(nonatomic,retain)NSString * someString; 

将创建setter以保留someString,在这种情况下,正确的方法是您的第一个方法。如果你使用:

  @property(nonatomic,assign)NSString * someString; 

你的第二个方法是正确的,因为它只会分配指针, p>

Which way is correct?

NSString *c = [[NSString alloc] init];
self.character = c;
[c release];

or

self.character = [[NSString alloc] init];

And why? Thanks.

解决方案

It depends on how your property is declared. If you used

@property (nonatomic, retain) NSString *someString;

The setter will be created to retain someString, in which case the correct way is your first method. If you used:

@property (nonatomic, assign) NSString *someString;

Your second method will be correct, since it will just assign the pointer and not retain anything.

这篇关于哪种方式是正确的方式分配内存与属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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