NSDictionary没有正确存储CGRect?

use*_*946 9 iphone objective-c ipad ios

我似乎有存储问题CGRectNSDictionary.我正在使用的代码:

dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"Crocodile", [NSValue valueWithCGRect:CGRectMake(100,100,200,200)], nil];
Run Code Online (Sandbox Code Playgroud)

从我读过的内容来看,我应该将其包装CGRect成一个NSValue并将其存储到字典中.

但是,当我尝试使用NSLog它时,该值将返回{{0,0},{0,0}}

NSLog(@"Crocodile value is: %@", NSStringFromCGRect([[dictionary objectForKey:@"Crocodile"] CGRectValue]));
Run Code Online (Sandbox Code Playgroud)

我检查了我的字典计数,似乎插入了项目.我不确定这在哪里失败了.我还试图通过创建一个CGRectvar,然后是一个NSValuevar 来手动分解它,并将其粘贴到具有相同结果的字典中.

任何帮助赞赏.谢谢

谢谢.

小智 19

参数的顺序应该是(object,key,object,key,...),所以在你的代码中对象是@"Crocodile",而key是rect.

交换它们应该有效:

dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
    [NSValue valueWithCGRect:CGRectMake(100,100,200,200)], // object first…
    @"Crocodile", // …then key
    nil];
Run Code Online (Sandbox Code Playgroud)

请注意,键不需要是NSString的实例,它们可以是符合NSCopying的类的任何实例.

  • @ user339946,但没有成功.自Mac OS X v10.0以来,该方法没有改变. (3认同)

sha*_*oga 11

你可以把它存储为NSString -

        NSStringFromCGRect(<#CGRect rect#>)
Run Code Online (Sandbox Code Playgroud)

然后恢复

         CGRectFromString(<#NSString *string#>)
Run Code Online (Sandbox Code Playgroud)

祝好运