2

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 SomeUIView 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!

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Note that a private implementation (a PIMPLE... my second favorite acronym next to NARC), won't actually hide the ivars... you can still get at 'em if you dig enough at runtime.
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.