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!

Frenzy
  • 21
  • 2

2 Answers2

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
teedyay
  • 23,293
  • 19
  • 66
  • 73
Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
  • 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. – bbum May 26 '10 at 00:43
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;
Sylvain G.
  • 508
  • 2
  • 9