开发者

iPhone static libraries: How to hide instance variable

I'm creating a static library to share using the following guide: http://www.amateurinmotion.com/articles/2009/02/08/creating-a-static-library-for-iphone.html

In one of the functions, I return a "SomeUIView" which is a subclass of UIView and is defined in the public header, however I don't want to expose the internal instance variable of SomeU开发者_Go百科IView in the public header.

I've tried using categories for a private internal header file for SomeUIView, but I keep running into "Duplicate interface declaration for class 'SomeUIView'".

Does anyone know how to do this?

Thanks!


Categories and extensions can't add instance variables to a class. I'd go for the PIMPL idiom here - use a private implementation object:

// header
@class MyObjImpl;
@interface MyObj {
    MyObjImpl* impl;
}
@end

// implementation file:
@interface MyObjImpl {
    id someIvar;
}
// ...
@end

// ... etc.

This also keeps your public interface stable in case you want to add something for internal use.

The "duplicate interface" comes from missing parentheses in the second interface declaration:

// header:
@interface MyObj 
// ...
@end

// implementation file:
@interface MyObj () // note the parentheses which make it a class extension
// ...
@end


You may also use the Objective-C 2 feature known as "Associative reference".

This is not really object-oriented API, but you can add/remove object to another object by using some simple functions of the runtime:

void objc_setAssociatedObject(id object, void * key, id value)

Sets the value or remove it when value is nil.

id objc_getAssociatedObject(id object, void * key)

Retrieve the value for specified key.

Note that this is also a mean to add "instance variable" to existing object when implementing a category.

Key is s simple pointer to private variable that you can declare as a module private by using:

static char SEARCH_INDEX_KEY = 0;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜