【发布时间】:2013-02-01 13:59:19
【问题描述】:
我有一个MKPolyline subblas,我想实现NSCoding,即
@interface RSRoutePolyline : MKPolyline <NSCoding>
I asked a question on the best way to encode the c-array and got an excellent answer。但是,MKPolyline 上没有定义 init 方法,即除了其类方法 polylineWithPoints:points 之外,没有其他方法可以为其提供数据。
这段代码我的评论可以吗?
- (void)encodeWithCoder:(NSCoder *)aCoder
{
MKMapPoint *points = self.points;
NSUInteger pointCount = self.pointCount;
NSData *pointData = [NSData dataWithBytes:points length:pointCount * sizeof(MKMapPoint)];
[aCoder encodeObject:pointData forKey:@"points"];
[aCoder encodeInteger:pointCount forKey:@"pointCount"];
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
NSData* pointData = [aDecoder decodeObjectForKey:@"points"];
NSUInteger pointCount = [aDecoder decodeIntegerForKey:@"pointCount"];
// Edit here from @ughoavgfhw's comment
MKMapPoint* points = (MKMapPoint*)[pointData bytes];
// Is this line ok?
self = (RSRoutePolyline*)[MKPolyline polylineWithPoints:points count:pointCount];
return self;
}
【问题讨论】:
-
您的
memcpy方向错误。目的地先行。您可以只使用[pointData bytes]而不是分配和复制数据。 -
@ughoavgfhw 谢谢,我已经编辑了我的答案.. 这条线是:
MKMapPoint* points = (MKMapPoint*)[pointData bytes];你说什么? -
__bridge_retained 需要吗?我对使用 c 桥接器感到困惑。
-
不,我相信普通的
__bridge就足够了。我在stackoverflow.com/questions/14854521/where-and-how-to-bridge/… 中解决了这个问题 -
我有 3 个很好的答案... 组合、类别和压倒一切的属性。 -我现在不知道该怎么办:)
标签: ios objective-c cocoa-touch nscoding