0

Basically what the title says. If I import a class header file, will this also include the implementation file in that import?

Basically I want to import the foodObject class into my view controller. However, in my .h file I have this declared:

#foodObject.h
@property (strong, nonatomic) NSMutableDictionary *foodDictionary;

and in the .m file i have this:

#foodObject.m
[foodDictionary setObject:@"1" forKey:@"Berries"];
[foodDictionary setObject:@"1" forKey:@"Beef"];
etc....

So my question would be if I imported my foodObject.h file into my view controller and instantiated a instance of the object, would it have a foodDictionary already with the above key-value pairs? If not how would I do this.

Harazzy
  • 201
  • 3
  • 11

3 Answers3

1

When performing an import, you only get what you expose in your class interface. That means that every property or method declared in your class interface (.h) will be publicly visible in other classes that import it.

If you want an instance of foodObject with the dictionary containing those fields, you should implement your init method, where you declare the addition of those strings to your dictionary. Do not forget to initialise it first, by

_foodDictionary = [NSMutableDictionary new];

[_foodDictionary setObject:@"1" forKey:@"Berries"];

[_foodDictionary setObject:@"1" forKey:@"Beef"];

Edit -

In your FoodObject.m file, you implement the init method:

- (instancetype)init {

if (self = [super init]) {

_foodDictionary = [NSMutableDictionary new];

[_foodDictionary setObject:@"1" forKey:@"Berries"];

[_foodDictionary setObject:@"1" forKey:@"Beef"];

return self;

}

This way, an instance of FoodObject generated like

FoodObject *foodObject = [[FoodObject alloc] init];

will automatically have an allocated foodDictionary property, containing the values you set in the init method.

Edit 2 - it is better to use immutable objects when declaring properties, as the mutable objects are not thread-safe. Further reading:

NSMutableArray is thread safe? (same goes for NSMutableDictionary)

Is Objective-C's NSMutableArray thread-safe?

Community
  • 1
  • 1
  • Thanks, which file do I add this code too? Also is this all the code I will need or is there other code as well? – Harazzy Sep 12 '14 at 13:24
0

if you do
self = [super init]; if(self){ [foodDictionary setObject:@"1" forKey:@"Berries"]; [foodDictionary setObject:@"1" forKey:@"Beef"]; }

in .m file

foodDictionary already with the above key-value pairs

林知易
  • 1
  • 2
-1

Yes, .m file is also imported. Just add your code

[foodDictionary setObject:@"1" forKey:@"Berries"];
[foodDictionary setObject:@"1" forKey:@"Beef"];

to the constructor of your class, and when you will instantiated a instance in property you will see your values. Also put @synthesize foodDictionary to .m file, to get access for foodDictionary propery.

nabiullinas
  • 1,185
  • 4
  • 20
  • 41