xcode NSNotification 用户信息示例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1032726/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 18:37:48  来源:igfitidea点击:

NSNotification userinfo example?

iosobjective-cxcodecocoacocoa-touch

提问by jdee

I have an array of objects that are positioned using CGPoints . At certain times in my app, an object in the array needs to notify other non-arrayed objects of its position. I understand that NSNotification is the best way to go, but I cant find a decent example of a 'sender' and 'reciever' for the notification that wraps and unwraps a CGPoint as userinfo. Can anyone help?

我有一个使用 CGPoints 定位的对象数组。在我的应用程序中的某些时候,数组中的对象需要将其位置通知其他非数组对象。我知道 NSNotification 是最好的方法,但我无法找到一个“发送者”和“接收者”的体面示例,用于将 CGPoint 包装和展开为用户信息的通知。任何人都可以帮忙吗?

回答by Peter N Lewis

In Cocoa Touch (but not Cocoa), CGPoints can be wrapped and unwrapped with

在 Cocoa Touch(但不是 Cocoa)中,CGPoints 可以用

+ (NSValue *)valueWithCGPoint:(CGPoint)point
- (CGPoint)CGPointValue

NSValues can be stored in the NSDictionary passed as the userinfo parameter.

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

For example:

例如:

NSValue* value = [NSValue valueWithCGPoint:mypoint];
NSDictionary* dict = [NSDictionary dictionaryWithObject:value forKey:@"mypoint"];

And in your notification:

在您的通知中:

NSValue* value = [dict objectForKey:@"mypoint"];
CGPoint newpoint = [value CGPointValue];

回答by Jasarien

The userinfo object passed along with the notification is simply an NSDictionary. Probably easiest way of passing a CGPoint in the userinfo would be to wrap up the X and Y coordinates into NSNumbers using -numberWithFloat:. You can then use setObject:forKey: on the userinfo dictionary using Xpos and Ypos as the keys for example.

与通知一起传递的 userinfo 对象只是一个 NSDictionary。在 userinfo 中传递 CGPoint 的最简单方法可能是使用 -numberWithFloat: 将 X 和 Y 坐标包装到 NSNumbers 中。然后,您可以使用 setObject:forKey: 在 userinfo 字典上使用 Xpos 和 Ypos 作为键,例如。

You could probably wrap that up into a nice category on NSMutableDictionary, with methods like setFloat:forKey or something...

您可能可以将其包含在 NSMutableDictionary 上的一个不错的类别中,使用 setFloat:forKey 之类的方法......