相关疑难解决方法(0)

如何在对象中使用objc_setAssociatedObject/objc_getAssociatedObject?

如果我在类别实现中使用objc_setAssociatedObject/objc_getAssociatedObject将模拟实例变量存储在setter方法中,那么我将如何访问getter方法中的键,因为setter方法中声明的任何变量都不在getter方法的范围内?

编辑:为了澄清,如果我使用以下模式,我应该在哪里声明STRING_KEY,以便我可以在setter和getter方法中使用它.

@interface NSView (simulateVar)
-(void)setSimualtedString:(NSString *)myString;
-(NSString *)simulatedString;
@end

@implementation NSView (simulateVar)

-(void)setSimualtedString: (NSString *)myString
{
    objc_setAssociatedObject(self, &STRING_KEY, myString, OBJC_ASSOCIATION_RETAIN);
}

-(NSString *)simulatedString
{
    return (NSString *)objc_getAssociatedObject(self, &STRING_KEY);
}

@end
Run Code Online (Sandbox Code Playgroud)

objective-c categories

65
推荐指数
6
解决办法
3万
查看次数

如何子类化没有指定初始化程序的类?

我试图继承MKPolyline。但是问题是,MKPolyline没有任何指定的初始化程序。这是我尝试做的事情:

import MapKit

class MyPolyline: MKPolyline {
    let locations: [Location]

    init(locations: [Location]) {
        self.locations = locations

        var coordinates: [CLLocationCoordinate2D] = []
        for location in locations {
            coordinates.append(location.coordinate)
        }
        super.init(coordinates: coordinates, count: coordinates.count)
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我Must call a designated initializer of the superclass 'MKPolyline'super.init通话中遇到了错误。据我所知,MKPolyline没有任何指定的初始化程序。

我该怎么办?如何子类化没有指定初始化程序的类?

swift

6
推荐指数
1
解决办法
632
查看次数

标签 统计

categories ×1

objective-c ×1

swift ×1