gpt4 book ai didi

ios - 实现 iOS 协议(protocol) - 只读属性

转载 作者:可可西里 更新时间:2023-11-01 04:36:28 29 4
gpt4 key购买 nike

我有一个来自 QuickLook 框架的协议(protocol):

/*!
* @abstract The QLPreviewItem protocol declares the methods that a QLPreviewController instance uses to access the contents of a given item.
*/
@protocol QLPreviewItem <NSObject>

@required

/*!
* @abstract The URL of the item to preview.
* @discussion The URL must be a file URL.
*/
@property(readonly) NSURL * previewItemURL;

@optional

/*!
* @abstract The item's title this will be used as apparent item title.
* @discussion The title replaces the default item display name. This property is optional.
*/
@property(readonly) NSString * previewItemTitle;


@end

/*!
* @abstract This category makes NSURL instances as suitable items for the Preview Controller.
*/
@interface NSURL (QLPreviewConvenienceAdditions) <QLPreviewItem>
@end

我正在尝试为只读属性 previewItemTitle 创建 getter 和 setter,以便我可以添加自定义磁贴:

.h

#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>

@interface QLPreviewItemCustom : NSObject <QLPreviewItem> {
NSURL * previewItemURL;
NSString *previewItemTitle;
}


@property(readonly) NSURL * previewItemURL;
@property (readonly) NSString *previewItemTitle;


@end

.m

#import "QLPreviewItemCustom.h"


@implementation QLPreviewItemCustom

@synthesize previewItemTitle;
@synthesize previewItemURL;


@end

这样,据我所知,我将只使用 synthesize 方法创建 getter。如何创建二传手?

最佳答案

如果只是在您要访问 setter 的 QLPreviewItemCustom 实现中,那么为什么不将类延续类别中的属性扩展为读写:

QLPreviewItemCustom.m

#import "QLPreviewItemCustom.h"

@interface QLPreviewItemCustom ()

@property (readwrite) NSURL *previewItemURL;
@property (readwrite) NSString *previewItemTitle;

@end

@implementation QLPreviewItemCustom

@synthesize previewItemTitle;
@synthesize previewItemURL;

@end

如果您想在任何地方都使用 setter,那么您将不得不使用不同的 ivar 名称并编写您的 getter,以便将原先的 getter 传递给新的。像这样:

QLPreviewItemCustom.h

#import <Foundation/Foundation.h>
#import <QuickLook/QuickLook.h>

@interface QLPreviewItemCustom : NSObject <QLPreviewItem> {
NSURL *url;
NSString *title;
}


@property (readwrite) NSURL *url;
@property (readwrite) NSString *title;

@end

QLPreviewItemCustom.m

#import "QLPreviewItemCustom.h"

@implementation QLPreviewItemCustom

@synthesize url;
@synthesize title;

- (NSURL*)previewItemURL {
return self.url;
}

- (NSString*)previewItemTitle {
return self.title;
}

@end

还值得指出的是,自己使用与另一个框架使用的类前缀相同的类前缀通常不是一个好主意。即不要将其称为 QLPreviewItemCustom - 将其称为 ABCPreviewItemCustom

关于ios - 实现 iOS 协议(protocol) - 只读属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9674113/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com