简体   繁体   English

如何在NSInvocation中存储一个初始化调用?

[英]How to store an init call in an NSInvocation?

I'm trying to set up an app that works with UIPageViewController. 我正在尝试设置与UIPageViewController一起使用的应用程序。 I technically could instantiate all the view at once and put them in an array, but that would be expensive, and it seems better to initialize the views as needed. 从技术上讲,我可以立即实例化所有视图并将它们放置在数组中,但这会很昂贵,并且根据需要初始化视图似乎更好。 I read that an NSInvocation is a message rendered static-- so I was thinking I could have an array that basically contains: [SubclassA alloc]init], [SubclassB alloc]init], etc... with those messages wrapped in an NSInvocation. 我读到NSInvocation是静态呈现的消息-所以我想我可以拥有一个基本上包含以下内容的数组: [SubclassA alloc]init], [SubclassB alloc]init], etc... ,这些消息包装在NSInvocation中。 I could then return the result of that message in pageViewController:ViewControllerAfter/BeforeViewController:. 然后,我可以在pageViewController:ViewControllerAfter / BeforeViewController:中返回该消息的结果。

I'm still pretty new at this, so it is very possible I am fundamentally misunderstanding NSInvocation, but either way, an answer would still be helpful. 我在这方面还很新,所以从根本上我可能会误解NSInvocation,但是无论哪种方式,答案仍然会有所帮助。

NSInvocation is for manipulating calls where you don't know the method or number/types of arguments until runtime. NSInvocation用于处理直到运行时才知道参数的方法或数量/类型的调用。 Here, the method called is fixed at compile time. 在这里,调用的方法在编译时是固定的。 You don't need NSInvocation . 您不需要NSInvocation

If you want to store an action to perform as an object that you can put into an array, you should use blocks. 如果要存储要作为对象执行的动作,可以将其放入数组中,则应使用块。

Sounds like you want some kind of lazy instantiation. 听起来像您想要某种惰性实例化。

You can use this helper class 您可以使用此帮助程序类

@interface LazyObject : NSObject

@property (copy) id (^block)(void));
@property (readonly) id object;

+ (instancetype)create:(id (^)(void))block;

@end

@implementation LazyObject {
    id _object;
}

+ (instancetype)create:(id (^)(void))block
{
    LazyObject *obj = [[self alloc] init];
    obj.block = block;
    return obj;
}

- (id)object
{
    if (!_object) _object = self.block();
    return _object;
}

@end

NSArray *array = @[[LazyObject create:^id{ return [[SomeClassA alloc] init];}],
                   [LazyObject create:^id{ return [[SomeClassB alloc] init];}]];

SomeClassA *a = [array[0] object];
SomeClassB *b = [array[1] object];

As others said, NSInvocation is not a good solution for your original problem. 就像其他人说的那样, NSInvocation不是解决您原始问题的好方法。 It is designed to invoke method dynamically. 它旨在动态调用方法。 You don't need it for most of the cases. 在大多数情况下,您不需要它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM