What's the difference between NSString *s = @“string” and NSString *s = [[NSString alloc] initWithString:@“string”]?

匿名 (未验证) 提交于 2019-12-03 09:13:36

问题:

I think the question is clear enough but still - what's the difference between:

NSString *string = @"Hello world!"; 

and

NSString *string = [[NSString alloc] initWithString:@"Hello world!"]; 

Let me know if this already answers it.

回答1:

NSString *string = [[NSString alloc] initWithString:@"Hello world!"]; 

Per cocoa as cocoa naming convention, You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy”. That means you own the string above, hence you're responsible to release the object.

NSString *string = @"Hello World"; 

The line above is a string literal / constant, you don't alloc it or release it. You don't own this object.



回答2:

NSString *string = [[NSString alloc] initWithString:@"Hello World!"]; 

This code creates a strong reference and the variable will be retained. It then assigns the value "Hello World!" to it.

NSString *string = @"Hello World!"; 

This code simply assigns the value "Hello World!" to the NSString object. It's not creating any references of any kind. If your object isn't already initialized and retained, the object will be destroyed at the end of the running scope.



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!