我需要在NSArray中存储对象的弱引用,以防止保留周期.我不确定使用正确的语法.这是正确的方法吗?
Foo* foo1 = [[Foo alloc] init];
Foo* foo2 = [[Foo alloc] init];
__unsafe_unretained Foo* weakFoo1 = foo1;
__unsafe_unretained Foo* weakFoo2 = foo2;
NSArray* someArray = [NSArray arrayWithObjects:weakFoo1, weakFoo2, nil];
Run Code Online (Sandbox Code Playgroud)
请注意,我需要支持iOS 4.x,__unsafe_unretained
而不是__weak
.
编辑(2015-02-18):
对于那些想要使用真__weak
指针(不是__unsafe_unretained
)的人,请查看这个问题:在ARC下归零弱引用
我曾经在调试器下使用[myVar retainCount]验证我的一些变量是否具有预期的保留计数,尤其是对于没有自定义dealloc的var.
你如何在ARC模式下这样做?你如何确保没有内存泄漏?
注意:我理解ARC应该为我处理这个问题,但生活远非完美,而在现实生活中,你有一些有时被第三方库分配的对象(使用retain?)并且永远不会被解除分配.
我这样做的图像:
MyObj *myObj=[[MyObj alloc] init];
Run Code Online (Sandbox Code Playgroud)
然后我打电话
[somethingElse doSomethingWithMyObj:myObj];
Run Code Online (Sandbox Code Playgroud)
后来,我做到了
myObj=NULL;
Run Code Online (Sandbox Code Playgroud)
如果我的程序工作正常,我的期望是myObj正在被销毁,但似乎并非如此......
那么我该如何跟踪这一点,特别是如果我没有管理的东西?
现在,关于工具:在我的mac(使用5 Meg)上运行内存工具似乎非常困难,无需重新启动mac并从头开始.这真烦人!即使在程序启动之前,仪器仍然会崩溃,那么是否有更改解决方案?
我在ARC
引用计数方面有点混乱你可以告诉我下面的波纹管代码的参考数量.
var vc1 = UIViewController()
var vc2 = vc1
var vc3 = vc2
weak var vc4 = vc3
Run Code Online (Sandbox Code Playgroud)
问题是:
有没有办法快速将对象的保留计数注销到Xcode的控制台?如果没有,那么下一个最佳选择是什么?
我正在开发一个iPhone应用程序,我刚刚创建了这个方法(它是在单例类中):
- (NSDictionary *)getLastPosts
{
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:http://example.org/last/]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *data_dict = [parser objectWithString:json_string error:nil];
// release stuff
[parser release];
[request release];
[response release];
[json_string release];
return data_dict;
}
Run Code Online (Sandbox Code Playgroud)
我是一个新手obj-c开发人员,所以我不确定这两件事:
data_dict
什么时候应该发布NSDictionary ?更新1
如果data_dict
是NSDictionary *data_dict = [[NSDictionary alloc] init]
,当我应该释放呢?
更新2
在调用者中我有这个:
- (void)callerMethod
{
NSDictionary *tmpDict = [mySingleton …
Run Code Online (Sandbox Code Playgroud)