NSNotification userinfo示例?

jde*_*dee 5 xcode cocoa cocoa-touch objective-c ios

我有一个使用CGPoints定位的对象数组.在我的应用程序中的某些时候,数组中的对象需要通知其位置的其他非排列对象.我知道NSNotification是最好的方法,但是我找不到一个像'发送者'和'接收者'这样的通知的好例子,用于包装和解包CGPoint作为userinfo的通知.有人可以帮忙吗?

Pet*_*wis 15

在Cocoa Touch(但不是Cocoa)中,CGPoints可以包装和解包

+ (NSValue *)valueWithCGPoint:(CGPoint)point
- (CGPoint)CGPointValue
Run Code Online (Sandbox Code Playgroud)

NSValues可以存储在作为userinfo参数传递的NSDictionary中.

例如:

NSValue* value = [NSValue valueWithCGPoint:mypoint];
NSDictionary* dict = [NSDictionary dictionaryWithObject:value forKey:@"mypoint"];
Run Code Online (Sandbox Code Playgroud)

在您的通知中:

NSValue* value = [dict objectForKey:@"mypoint"];
CGPoint newpoint = [value CGPointValue];
Run Code Online (Sandbox Code Playgroud)

  • 在Cocoa中,您可以使用NSPointFromCGPoint,然后使用NSValue的valueWithPoint:和pointValue. (2认同)