NSDictionary available between two methods - objective-c

The title pretty much explains it all.
I simply have an NSDictionary initialised with a bunch of keys and values in one method, but I would like another method to be able to access it within the same class. Is this possible?

Uhm, ever heard of such amazing and totally new and never before seen concepts such as instance variables and properties?
#property (nonatomic, copy) NSDictionary* mySharedDictionary;

Define your NSDictionary as a property (mine called 'dictionary')either in your .h or .m file. Initialise it anywhere in your code and call it with self.dictionary, goodluck!

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.

How to access protected variable in Objective-C?

I know protected variable can't be access out side the class but is it possible to access them in Category or in SubClass, I think it's not possible for Subclass but is it the same case for Category ?
What I want to do is some modification to a library form github but I don't want to modify the original source code. I want to achieve this through subclassing or using category but the problem is I want reference to some protected variable.
Protected variable in .m file:-
#interface Someclass() {
NSMutableDictionary *viewControllers;
__weak UIViewController *rootViewController;
UIPageViewController *pageController;
}
#end
A category cannot access private instance variables nor can a subclass do that.
As you have access to the source code and just don't want to change the original source code you could create another class with exactly the same data structure. (same variable names and types declared exactly in the same way and sequence).
#interface Shadowclass() {
NSMutableDictionary *viewControllers;
__weak UIViewController *rootViewController;
UIPageViewController *pageController;
}
#end
Then add getters and setters to Shadowclass to make the values accessible.
The do:
Someclass *someclass = ... // you get the object from somewhere somehow.
object_setClass(someClass, [ShadowClass class]);
How someclass is of the type ShadowClass and you can access the getter and setter. Frankly I am not sure how the current compiler allows for accessing the getters directly of if you are allowed to cast someClass now an ShadowClass type object variable, but you can use performSelector for accessing the getters or setters.
Accessability of getters and setters directly like [shadowClass rootViewController:xxx] may even vary whether you are using ARC or not. (The compiler's behaviour here may even be configurable. This, too, I do not know on detail out of the top of my head.)
However, I am not sure whether I really want to recommend that! You may find less "hacky" alternatives.
And do not underestimate the importance of creating exactly the same structure for Shadowclass as for Someclass!

When should I declare an instance variable rather than property in the header? [duplicate]

This question already has answers here:
Do declared properties require a corresponding instance variable?
(6 answers)
Closed 8 years ago.
For example, in the following codes.
#interface TUTViewController : UIViewController
{
NSTimer *timer;
}
#end
and
#interface TUTViewController : UIViewController
#property (weak, nonatomic) NSTimer *timer;
#end
In which scenario do we use the first method to declare variable?
You are going to get lots of opinions on this, often stated as hard fast rules.
Example:
Maddy: Never put ivars in the .h. ivars should always be private
meaning they do not belong in the public .h. If you create ivars, put
them in the .m file
I have tremendous respect for Maddy, but I disagree with him on this one.
If you put your iVars in your .m file, they are hidden from other classes, but they are also hidden from subclasses that you create.
I prefer to mark my instance variables as #protected, which makes them available to subclasses, but not to other classes.
Others will tell you to make EVERYTHING a property. Before ARC, it made sense to save all your objects in properties, since you could use the setter on the property to manage the memory on your objects. (When assigning a value to a retained property, the setter would first release any old value, then retain the new value.) Now ARC takes care of that for you even for iVars, so the argument for making everything a property is less.
What I do is to make everything an iVar, unless:
I need a custom getter or setter method with special behavior.
I want to access the value from another object.
I need to mark a property as "atomic" for access from another thread. (get in the habit of declaring all of your properties as "nonatomic." If you don't know what atomic is for for, you want nonatomic. Atomic properties are slower than nonatomic.)
As a matter of policy I NEVER access another object's iVars except trough a property.
There is a small but real amount of overhead in using a property rather than an instance variable. A property read/write always makes a method call. An iVar accesses the memory directly without the overhead of a method call. Usually the difference is too small to matter. But, if you're doing millions of operations, like doing something to every pixel in a large image, or handling callbacks from processing video or audio samples in real-time, the difference can be large.
I would highly suggest to use #properties unless there is a very good reason not to. It's true the discussion is a religious one more than a technical one but since we are probably all followers of the Cult of Mac, if Apple prefers you to use #properties then that's the standard. In my opinion both Apple documentation and Xcode aren't as pushy on standards like ReSharper would do in Visual Studio for instance (it warns when you don't use var for example). That's a pity because that would make it easier for me to pick up code after somebody else.
There is a way to "hide" #properties in a .m file, you should declare it as follows:
#interface ABCMySpiffyClass ()
#property (weak, nonatomic) IBOutlet UIImageView *spiffyImage;
#property (weak, nonatomic) IBOutlet UILabel *spiffyTitle;
#end
These are not completely private to another consumer of your class but it is hidden at first sight. This should tell the other developer that he or she should not use them. I think public/private has more to do with documentation as it has to do with application security for most apps.

Why do I declare properties twice? or do I?

Sorry for the kind of useless post title, but since I'm not really sure what I am doing, that was the best i could come up with.
In my header file it looks like this
#interface RootViewController : UITableViewController {
NSMutableArray *eventsArray;
}
#property (nonatomic, retain) NSMutableArray *eventsArray;
#end
This is not all the properties but i removed all but one for simplicity.
I'm doing this by following a guide from apple developer. It seems as though the guide is not totally updated since it tells me to synthesize properties, wich i should not have to anymore right?
Anyways, why is it like this? To me, a beginner at this, it seems as though I declare the property twice? Or do I do something else at the first row there?
It's like this for historical reasons, with the older compiler.
You can do this nowadays:
#interface RootViewController : UITableViewController
#property (nonatomic, retain) NSMutableArray *eventsArray;
#end
The way you have it, you are declaring an instance attribute, and then you are saying you want to automatically generate getters and setters.
Nowadays, you can just say you have a property and the compiler will automatically generate the instance attribute at compile time. It removes the apparent redundancy.
To me, a beginner at this, it seems as though I declare the property
twice? Or do I do something else at the first row there?
A property and the instance variable that backs it up (if there is one) are two different things. A property is really just a promise that the class provides certain accessor methods. So the fact that you had to declare the property and ivar separately isn't strange. However, most properties are, in fact, backed by an ivar with a related name, and writing and maintaining the two separately got to be a chore. So Apple added ivar synthesis to the compiler, so that the compiler generates an ivar for any synthesized properties for which an ivar doesn't already exist. Also, because synthesized accessors are by far the most common, and because the compiler will use any accessors that you provide even if a property is marked #synthesize, that became the default so that you no longer need the compiler directive.

why to declare some instance variables as properties

Though this is somewhat a very basic question but I have some doubts still left after reading so many documents and questions on stackoverflow.com.
I want to know why to declare some instance variables as properties.
MYViewController.h
#interface MyViewController : UIViewController {
UIButton *btn;
NSString *name;
}
#property (nonatomic, retain) UIButton *btn;
#property (nonatomic, retain) NSString *name;
MyViewController.m
#implementation MyViewController
#synthesize btn;
-(void) viewDidLoad()
{
[btn setTitle:#"Hello" forState:UIControlstaeNormal]; //this is first way where there is no need to declare btn as property
[self.btn setTitle:#"Hello" forState:UIControlstaeNormal]; //this is second way where we do need to decalre btn as property as we are accessing it through self
//Setting value of name
name = #"abc"; //this is first way where there is no need to declare name as property
[self setName:#"abc"; //this is second way where we do need to declare name as property as we are accessing its aetter method through self
}
Now in the above code I wanna know when we can use the getter/setter methods of btn variable without declaring it as property then what is the need to declare it as property and which is the better way to set the value of "name".
Somewhere I read that when you want your instance variables to be accessed my other class objects then you should declare them as instance variables. Is it the only situation where we should declare them as properties.
Basically I am a little confused about in which situations to declare the instance variables as properties.
Please suggest.
Thanks in advance.
In short, you don't have to declare instance variables as properties unless you want to.
You declare a variable as a property in order to auto-generate getter and setter methods. In your property declaration you can specify how you want them set up (retain vs assign, atomic vs nonatomic). Then, the getter and setter are generated with the #synthesize directive.
So, again, there is no right or wrong way to use properties. Some people never use them, some people make every variable a property. It's really up to you.
typically, you'll use them because:
1) the property belongs in the public interface of the class
used when the class needs to expose a given method. the downside is that clients and subclasses may abuse the public interface (all objc methods are public, where visible), unless you're careful to hide these details (which is also a pain at times). sometimes you're forced to go well out of your way in order to achieve the class interface you need (with the proper levels of visibility).
2) you want auto-generated accessors
implementing nonspecialized accessors is tedious, and error prone. it's better to save the time and let the compiler generate them for you.
3) to document behavior
sometimes it's better to write #property (copy) NSString * title; instead of over-documenting the expected result.
4) stricter selector matching with dot-syntax
the compiler performs stricter selector matching. prefer to catch the errors/issues at compilation, if possible.
5) to force the subclasses to use them instead of handling the ivars directly
objc ivars are protected by default. you'll often want them to be private (depending on how the class is used and distributed, or just to ensure the subclass uses the base class correctly).
there are a ton of reasons for this. threading and maintenance are the big ones.
if you declare the ivar as private and provide a property for the subclass to use, then the subclass is forced to use the property in their implementation (although there are ways they could cheat) rather than giving them direct access to the ivar.
so... it ultimately depends on your preference, and the implementation details of your class, paired with the interfaces you're using. i don't think there's a hard and fast rule here - lesser evils and convenience are key motivations.