当在Cocoa中声明对象时,我应该将它们设置为nil吗? [英] When declaring objects in Cocoa, should I set them to nil?

查看:116
本文介绍了当在Cocoa中声明对象时,我应该将它们设置为nil吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我想创建一个 NSString 的实例,它根据另一个变量的值被初始化为一个特定的值。通常,我会

Say I want to create an instance of NSString, which is initialized to a certain value depending on the value of another variable. Normally, I would do

NSString *string;
if(foo == 1)
    string = @"Foo is one.";
else
    string = @"Foo is not one.";

但是,在我看过的一些示例代码中, >

However, in some sample code that I've seen, I've seen people do

NSString *string = nil;
if(foo == 1)
    string = @"Foo is one.";
else
    string = @"Foo is not one.";

这两者之间有什么区别,哪种方法更好?

What is the difference between these two, and which method is preferred?

推荐答案

我的个人偏好是立即初始化任何变量。

My personal preference is to initialize any variable immediately. However, in the sample you provided, these two methods are equivalent.

C 语言中(即<$ c未立即初始化的$ c> C , C ++ Obj-C )可以包含随机垃圾值。在初始化之前使用变量会导致意外的行为(从希望崩溃到获得意外行为)。

In C languages (i.e. C, C++, Obj-C) variables that are not initialized immediately may contain random garbage values. Using the the variable before it is initialized lead to unexpected behavior (ranging from hopefully crashing to getting unexpected behavior).

示例
考虑下面的例子:

Example Consider the following example:

int abs;
if (argument > 0) abs = argument;
else if (argument < 0) abs = -1 * argument;
NSLog(@"%i", abs);

这里的代码留下 abs variable uninitialized if 参数为0.因此,您将获取记录的随机值,然后导致破坏程序其余部分的值;并且很难检测到问题所在!

Here the code leaves abs variable uninitialized if argument is 0. So you would getting random values logged and then lead to corrupting the values in the rest of the program; and it would be hard to detect where the problem is!

如果使用未初始化的引用,则很可能会得到 EXC_BAD_ACCESS

If you use an uninitialized reference, you would most likely get a EXC_BAD_ACCESS.

这篇关于当在Cocoa中声明对象时,我应该将它们设置为nil吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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