Unexpected content in default files generated for opengl template in xcode - objective-c

I was just starting a new opengl project in xcode. When I was going through the default files created, I was confused by this following line of codes in the viewController interface.
#interface RetinaTestViewController ()
#property (nonatomic, retain) EAGLContext *context;
#property (nonatomic, assign) CADisplayLink *displayLink;
- (BOOL)loadShaders;
- (BOOL)compileShader:(GLuint *)shader type:(GLenum)type file:(NSString *)file;
- (BOOL)linkProgram:(GLuint)prog;
- (BOOL)validateProgram:(GLuint)prog;
#end
My question is why this is written in the implementation of viewController rather than in the interface itself. This may be very basic but I just started to work with the openGL stuff. Please do help.

I don't think this is really OpenGL related, but Objective-C has something called categories, which allow you to add extra methods to an existing class. You can add them to any class you want, whether you have the source code or not. The syntax looks like:
#interface classname (categoryName)
- (void)extraMethod1;
- (void)extraMethod2;
#end
#implementation classname (categoryName)
- (void)extraMethod1
{
}
- (void)extraMethod2
{
}
#end
And, as I say, you can use that to add methods to any class, including e.g. NSString, NSDictionary and the other Foundation objects.
The brackets after the classname in the interface declaration dictate that this is a category, not a full interface definition. Historically there was no way to add extra storage to a class through a category, so you may not declare member variables in categories. Hence there's no {} section.
In the modern runtime (on 64bit OS X and iOS), you can add extra storage via #properties, as Apple appear to do in the code you've given.
Here Apple are using category methods to create something like private methods — in this case methods that everyone in the class knows are there but which aren't declared externally. That's a design decision, to keep the bits that other people are likely to look at neat and to indicate the programmer's intent.
What's going on is that:
the bits of RetinaTestViewController that Apple want everyone else to know about are declared in the header file
the bits that aren't meant to be exposed are declared only in the implementation file
A well-designed object should expose a public interface and conform to that interface, while doing whatever is necessary internally and keeping its internals secret.
You can read a little more category methods here, here and here (scroll down to number 11).

Related

Objective-C : Accessing fields in implementation

Is it possible to fields defined only in implementation but not in interface definition ?
#interface MyInterface .... #end --> dict not defined here!!!
#implementation MyInterface
...
NSDictionary *dict;
...
#end
In this case if somewhere I somehow accessed to this class, can I access to the dict or should I create a getter just like in Java ?
Edit after #Rob's answer
Thanks for the answer Rob, I wish I have the implementation of these interface and classes. Instead I am trying to bind two different libraries ( I know it is reallllly bad as architectural point of view but this is where I end up).
Basically, I am in react-native world. And we are using react-native-video as our player layer. But since AVPlayer does not support some subtitle types our head company sent us a library that needs a player instance and a view instance to draw subtitle on the view. I believe they will bind to events of the player and draw sub titles based on player states.
So react-native-video is in this github repo with the interface and implementation.
I find the UIView that includes the properties and casted it to the object itself RTCVideo in this case). But now I am stuck. I can go and change some stuff as per your suggestion in the "Development Pods" to be able to access but this is my last bullet :) I prefer to convince these two libraries in a friendly way :)
Yes, but the above syntax isn't what you want. The modern way to do this is with a class extension.
Your header file is the same:
#interface MyInterface
#end
But in your .m file, you create an extension by appending ():
#interface MyInterface ()
#property (nonatomic, readwrite) NSDictionary *dict;
#end
Now, inside your .m file, you can access self.dict normally, but outside of your .m file it won't appear available.
For full details, see Programming with Objective-C: Class Extensions Extend the Internal Implementation.
The syntax you've written actually creates a static (global) variable called dict that isn't tied to any instance.
It is possible to create raw instance variables using a {...} syntax, either on the extension or on the implementation, but this isn't used that often today, except for managing raw buffers that you don't want accessors for. The syntax is either:
#interface MyInterface () {
NSDictionary *_dict;
}
...
#end
or on the implementation:
#implementation MyInterface {
NSDictionary *_dict;
}
...
#end
But I recommend simple extensions with properties any time you can. And if you are considering creating an accessor for it, you definitely want to use #property and let the system do it for you.
If I understand your edits correctly, you're trying to read the internal ivars of an object that doesn't expose them with an accessor, correct? I believe specifically you want to access _player.
There's several common ways to do that. The key feature you want is Key-Value Coding.
The simplest approach for this problem is -valueForKey:
AVPlayer *player = [view valueForKey:#"player"];
The first thing -valueForKey: looks for is _<key>, and if it's just an object pointer (as in this case), it just returns it.
(This can be broken if a class return false for +accessInstanceVariablesDirectly, but the default is true, and it's unusual to override this.)
Another very common approach is to just declare any methods you know exist as a category. (This won't work for _player, since it's not a method, but in case you need similar things.) Imagine you wanted to call the "private" method -removePlayerTimeObserver. In your .m file, just say you know about it using a category:
#interface RCTVideo (PrivateMethods)
- (void)removePlayerTimeObserver;
#end
And since you know about it, you can call it:
[video removePlayerTimeObserver];
If you're wrong, and that method doesn't really exist, then the program will crash. In Objective-C, almost all rules are advisory. You can break them if you want to. ObjC programmers tend to be big rule-followers because otherwise the program crashes and ObjC has very clear rules that are pretty easy to follow. It's not because the system forces us to.

Explaning syntax for #property id<delegateName>

I see a lot of code references when writing delegates using something likes
#property (nonatomic, weak) id<mySuperCoolDelegate> delegate;
normally where id<mySuperCoolDelegate> is, is the data type of the property. So the questions are:
Is my understanding correct, that above syntax is telling the compiler data type of the id is mySuperCoolDelegate?
Any other examples where this sort of code (data type specified for id) could be used?
Thanks!
This piece of code is objective-c's way of implementing interfaces (as in Java or Go). using "id" means that you don't know at compile time what type of object it will be. But using the protocol in angle brackets you are telling the compiler that no matter what object it will be, it will need to support the 'mySuperCoolDelegate" protocol. If it doesn't - the compiler will let you know.
This syntax tells the compiler that delegate is of some kind of class (any class) that implements the mySuperCoolDelegate protocol.
This allows a certain component to notify another component on some event that happened without the need to know about the notified component (type-wise). (e.g. UITextView notifies its controller that the text has been changed without having a reference to that controller, only through the generic-typed delegate so the UITextView does not need to limit itself to a specific controller's type)
Also note that delegates are usually declared as weak (rather than strong). If an instance of UIViewController has a strong reference to a UITextView instance and that text view delegate (assume it is strong) is the controller instance then you will have a retaining cycle where both objects release will be dependent on the other object's release (which will never happen and leave you with a memory leak).
Short:
This tells the compiler that the property can be of any type as long as it implements the protocol mySuperCoolDelegate.
Still too short to be 100% accurate but easy to understand:
id is similar to NSObject*, meaning it is a reference to any kind of object (not only subclasses of NSObject, to be frank). Witin <> you declare which protocols the object has to conform to.
Example: It could be both:
#interface mySuperCoolClass : <mySuperCoolDelegate> ... #end
or
#interface somebodyElsesSuperCoolClass : <mySuperCoolDelegate> ... #end
Wherever you use that property, the compiler will allow you to access all methods that are declared in the related #protocol (most likely in some .h file that you need to #include).

Multiple #interface declarations generated by Xcode for NSViewController?

I am making a Cocoa application, and using Xcode for various code-generation. Works fine for generating .h and .m files for subclassing UIView, but when i subclass UIViewController i get an #interface declaration identical in both files, except that in the .m file it has ( ) at the end:
//in MyViewController.h
#interface MyViewController : NSViewController <MyViewDelegate>
#end
but also
//in MyViewController.m
#interface MyViewController ()
#end
#implementation MyViewController
#end
Yet it compiles fine. So, assuming this is normal behavior, the two-parts of question are:
(A) Why does this happen, and
(B) What are the results -- especially in terms of compile order?
Thanks!
when i subclass UIViewController i get an #interface declaration identical in both files, except that in the .m file it has ( )
As you noticed, the two interface blocks are not identical -- the () is important. The one with the () is a class extension, which is similar to a category without a name. The two important differences between a category and a class extension are:
You can declare instance variables in a class extension, but you can't in a category.
A class extension must appear in the same file as the implementation block.
Class extensions are useful for declaring instance variables and methods that you don't want to expose in the header file, such as methods or variables that are specific to the implementation and shouldn't be relied upon by users of the class.
Are you familiar with Categories? What you are observing is similar, but has important distinctions from Categories. The distinction here is that it is anonymous (hence the empty parens) and compiled at the same time the original class is compiled. That later part is an important part: it means you can add instance properties (storage). This is most commonly used to declare "internal only" or "private" methods and properties. But keep in mind that at runtime there is no notion of 'private' enforcement, it's all about what interface you have published vs. not published. This is just one way to have very clearly defined interface that is only 'published' to people who author the implementation file of the core class.

Can we not declare methods in the header files?

I am watching the Stanford University iPad and iPhone application Developments course video. The instructor says in the video we can control-drag an UI object to the implementation files to create an action. But in this way the method will not declare in the header file. Does this mean it is ok to implement methods in the .m file but not declare in the .h file?
Depends on how you define "ok" :-)
Objective-C uses dynamic method lookup and does not really enforce access ("private", "public", etc.) specifiers. So you don't need to declare any method in a header file.
However you will end up fighting the compiler as it does do a fair amount of type-checking unless you persuade it not to, and you'll lose by doing so.
You are not required to declare in the header file all methods in the implementation. But if not in the header file obviously you cannot reference them by literal name in another file, nor can you "forward reference" them in the implementation file.
(Note that this is not that different from regular C, but is different from methods of a class in C++.)
It's "OK" to not declare methods in the header yes, under certain circumstances. For instance, if using ARC then the compiler generally needs to know the method signature so it can do the right thing. But basically all it means is that wherever you're using the method, it must already know about the method you're calling.
Since you're talking about Interface Builder, that's slightly different in that it will know about all methods since it can "see" the whole context of your header and implementation files and know that a method exists. i.e. in my terminology above, the method has been defined before it's used.
With regard to defining before use, the general accepted approach is to either:
Define a method in the interface file (.h). e.g.:
MyClass.h
#interface MyClass : NSObject
- (void)someMethod;
#end
MyClass.m
#implementation MyClass
- (void)someMethod {
// do something
}
#end
Define a method in a class continuation category. e.g.:
MyClass.h
#interface MyClass : NSObject
#end
MyClass.m
#interface MyClass ()
- (void)someMethod;
#end
#implementation MyClass
- (void)someMethod {
// do something
}
#end

Process of transitioning a project from a collection of classes to a .dylib?

I've been working on a pet project for a few weeks now, and starting to think that it may get used by myself and a few friends. At present, it's really just a pile of Objective-C classes in an XCode project with a main() I've been using to test various features. Going forward it seems easiest to use this library in projects if I package it up as .dylib file. As I've found with other languages, doing this as an afterthought is a nuisance that ideally is farmed out to the lowest rung. :)
I'm very new to the Objective-C/Xcode world, but according to Apple's "Dynamic Library Programming Topics", I'm under the impression that it's really just a matter of rejigging my interface files to be of the format:
#protocol Person
- (void)setName:(NSString*)name;
- (NSString*)name;
#end
#interface Person : NSObject <Person> {
#private
NSString* _person_name;
}
#end
(taken from referenced Apple doc).
Where: I'm defining a protocol that contains the methods I wish to include for the classes to be contained in the .dylib, and then defining an interface that subclasses NSObject implementing the aforementioned protocol and declaring ivars in here.
A few questions:
Am I able to omit methods from the protocol that I don't wish to "EXPORT" to the dylib?
If I have subclasses of a class within the dylib, do I create another protocol for the subclass, and make the superclass of the newly created class implement that protocol? For instance, if I were subclassing person:
#protocol CatPerson
/* any additional methods for CatPerson not in Person */
- (void) protractClaws;
- (void) retractClaws;
#end
#interface CatPerson : Person <CatPerson> {
#private
/* any additional ivars for CatPerson not in Person */
NSNumber *clawCount;
}
It's likely a very trivial question, but I'm trying to figure out everything I'll need to do before I go thru the gnashing of teeth of moving all the classes to a .dylib.
Project->New Target… select "dylib" in the panel that you get. Make it the current target. control-click on the groups & files tableview header, check "target membership". Check the boxes next to the files you want included in your dylib.