我有一个 NSDictionary 可能会在循环内设置。在循环结束时,我想查明字典是否已定义。下面是一个例子:
NSDictionary *myDict;
for (int i=0; i < 100; i++){
if (thisCondition){
myDict = [NSDictionary dictionaryWithObjectsAndKeys:etc, nil];
}
}
if (myDict) {
[self doSomething];
}
不幸的是,无论 myDict 是否已被分配,myDict 的测试每次都会通过。尝试将任何方法传递给 myDict,例如 [myDict count],请给出 exc_bad_access,因为它尚未分配。所以这是一个无人区。
有办法做到这一点吗?我意识到我可以切换到 NSMutableDictionary,定义它,在循环中添加到它,并测试计数,但这不是我的偏好。
I have a NSDictionary that might be getting set inside a loop. At the end of the loop I want to find out if the dictionary has been defined. Here is an example:
NSDictionary *myDict;
for (int i=0; i < 100; i++){
if (thisCondition){
myDict = [NSDictionary dictionaryWithObjectsAndKeys:etc, nil];
}
}
if (myDict) {
[self doSomething];
}
Unfortunately, the test of myDict passes every time, whether myDict has been alloc'ed or not. Trying to pass any methods to myDict, like [myDict count], give a exc_bad_access because it has not been alloc'ed. So it is kind of a no man's land.
Is there a way to accomplish this? I realize I could switch to a NSMutableDictionary, define it, add to it in the loop, and test for a count, but that is not my preference.
发布评论
评论(1)
首先,确保将指针初始化为 nil:
否则,对有效指针的检查可能不起作用。
First, make sure you initialize your pointer to nil:
otherwise, your check for a valid pointer may not work.