iphone ARC - 如何将对象设置为零?

发布于 2024-12-29 10:13:51 字数 257 浏览 4 评论 0原文

我有一些逻辑来测试一个对象是否为零,如何将其设置为零?

喜欢:

// in some method
if (true){
 [self myObj] = [[myObj alloc]init];
} else{
 [self myObject] = nil; //??? How to do this with Automatic Ref. Counting
}

// elsewhere
if([self myObj]){

}

I have some logic that test if an object is nil or not, how can I set it to nil?

Like:

// in some method
if (true){
 [self myObj] = [[myObj alloc]init];
} else{
 [self myObject] = nil; //??? How to do this with Automatic Ref. Counting
}

// elsewhere
if([self myObj]){

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

抱猫软卧 2025-01-05 10:13:51

您的代码不正确。

您需要使用属性并为其赋值,例如 [self setMyObject:nil];[self setMyObj:[[myObj alloc] init]];

Your code is incorrect.

You need to use properties and assign values to them, like [self setMyObject:nil]; or [self setMyObj:[[myObj alloc] init]];.

野の 2025-01-05 10:13:51

你的代码是错误的。尝试:

self.myObject=nil;
//or
[self setMyObject:nil];

另外,请确保 myObject 是您的类中的属性,否则使用 self 将不起作用。

Your code is wrong. Try:

self.myObject=nil;
//or
[self setMyObject:nil];

Also, make sure that myObject is a property in your class, otherwise using self won't work.

淡莣 2025-01-05 10:13:51

[self myObj] 不可赋值,因为它不是左值。要解决此问题,请引用基础变量,例如 self->myObj,或者在使用属性时使用 [self setMyObj:]

[self myObj] is not assignable, as it is not a lvalue. To fix this, either reference the underlying variable, e.g. self->myObj, or use [self setMyObj:] if you are using properties.

携余温的黄昏 2025-01-05 10:13:51

您正在使用 getter 作为 setter。那是行不通的。应该是

[self setMyObj:[myObj alloc]init]]; 

并且

[self setMyObj:nil];

假设您已经实现了设置器。在 ARC 下,如果您只是访问 ivar,则实际上不需要这样做 - 您可以直接访问它,并且将为您完成引用计数:

myObj = [MyObj alloc] init];

并且

myObj = nil;

将为您设置和删除所有内容。

You are using a getter as a setter. That isn't going to work. It should be

[self setMyObj:[myObj alloc]init]]; 

And

[self setMyObj:nil];

Assuming you have implemented the setters. Under ARC you don't really need to if you are just accessing an ivar - you can access it directly and the reference counting will be done for you:

myObj = [MyObj alloc] init];

And

myObj = nil;

Will set and remove everything for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文