In Objective-C, I'm curious how access controls for instance variables, like #private,#protected, etc. are implemented.
I had considered that separate structures were being generated in some way like this:
#interface Foo {
int bar;
#private
int baz;
#public
int qux;
}
=> something along the lines of
struct Class_Foo_Protected {
int bar;
};
struct Class_Foo_Private {
int baz;
};
struct Class_Foo_Public {
int qux;
};
But I really have no idea. Anyone know how this was really done?
Those modifiers don’t change anything about the memory layout of your class. The compiler itself remembers which ivar is public, protected or private and emits errors if you try to access them from somewhere inappropriate. This is all done before any code is generated and doesn’t affect the generated code.
Related
We usually do things lik
- (void)setFoo:(Foo *)foo
{
_foo = foo;
// other computation
}
Getter and Setters give me warning that I cant set my own property. I am guessing it needs a computed property. What would be the best way to translate this idiom in Swift?
If you're doing computation tightly integrated with setting the internal storage of foo, especially if setting the storage is conditional on such computation, the computed-property/stored-property pair #matt suggests is probably the solution you need.
Otherwise—if you need to need to do work unconditionally in response to the setting of a property—what you're looking for is Swift's property observers feature.
var foo: Foo {
willSet(newFoo) {
// do work that happens before the internal storage changes
// use 'newFoo' to reference the value to be stored
}
didSet {
// do work that happens after the internal storage changes
// use 'oldValue' to reference the value from before the change
}
}
You can "shadow" a public computed variable with a stored private variable, like this:
private var _foo : Foo!
var foo : Foo {
get {
return _foo
}
set (newfoo) {
_foo = newfoo
}
}
That is the analogy to what Objective-C #synthesize does. But you should also ask yourself whether you really need this. In most cases, you don't.
I have classes with many properties, which consists, in some cases, other complex classes. Not allways I'm going to use this complete schemas, but sometimes I'm doing so. What's the best practice to create an object, deal with it and then retrieve information on demand?
I'm giving an very simple example to clarify:
Supose a class student which is related to a class professor. This class is related to other classes like classes, schedules, etc. Not allways I will need to use all this information.
Ough I to mantain the professor's ID in object student and then load the information when I need? Should I create a property just for storing the professorID, or I create a new professor object without loading all other data into it, just storing the ID? Or neither? What's the best practice?
Thanks.
Use the lazy loading pattern.
Suggestion 1
Does your application requires to save & load the values of the objects & properties ( also known as "to serialize" or "to persist" ) ?
Does your application requires to have several instances of the same class ?
If the answer to this questions is true, seems you need to store your data in a D.B., as #larsmans suggest.
Suggestion 2
Another thing. You didn't mention what programming language are you using. In programming languages like C++, Delphi (Object Pascal), D, an object inside another object can be handled in 2 ways: as part of the object, or as a pointer to the subobject.
I suggest use pointers to objects approach, for your scenario.
In programming languages like Java, PHP, C#, VB.NET, there is this concept called references, which in practical terms, its the same as pointer to objects, so you don't need to do anything else.
Non pointer example:
class SubClass
{
public:
int X;
int Y;
}; // class SubClass
class MainClass
{
public:
int Color;
SubClass SubObject;
public:
/* constructor */ MainClass()
{
this.Color = 7;
this.SubObject();
} // /* constructor */ MainClass(...)
/* destructor */ ~MainClass()
{
this.~SubObject();
this.Color = 0;
} // /* destructor */ MainClass(...)
}; // class MainClass
void main()
{
MainClass* MainObject = new MainClass();
MainObject->Color = 5;
MainObject->SubObject.X = 19;
MainObject->SubObject.Y = 32;
delete MainObject();
} // void main(...)
Pointer to objects example:
class SubClass
{
public:
int X;
int Y;
}; // class SubClass
class MainClass
{
public:
int Color;
SubClass* SubObject;
public:
/* constructor */ MainClass()
{
this.Color = 7;
this.SubObject = new SubClass();
} // /* constructor */ MainClass(...)
/* destructor */ ~MainClass()
{
delete this.SubObject();
this.Color = 0;
} // /* destructor */ MainClass(...)
}; // class MainClass
void main()
{
MainClass* MainObject = new MainClass();
MainObject->Color = 5;
MainObject->SubObject->X = 19;
MainObject->SubObject->Y = 32;
delete MainObject();
} // void main(...)
Cheers.
In the general case, you will need some entities joining the entities from your domain. Say, you will have a StudentRegistry that will hold the correspondence between the students and their professors/lecturers. This indeed resembles an RDBMS schema design, so you can refer to the ER DB design method (obviously, you will have classes instead of tables.)
It sounds like you are describing lazy loading.
I'm relatively new to Objective-C and I have an enum with a corresponding array of string descriptions:
typedef enum {
kCoverage = 0,
kSingulation,
kPopulation,
kDownforce,
} MapTileType;
static NSString* const kMapTileTypeString[] = {
[kCoverage] = #"Coverage",
[kSingulation] = #"Singulation",
[kPopulation] = #"Population",
[kDownforce] = #"Downforce",
};
I'm discovering that I actually need to define behavior for the "type" of map tile. For instance, I have a tile rendering behavior that applies to a specific type of map tile.
static RenderingStrategy* const kMapTileTypeRenderingStrategy[] = {
[kCoverage] = ...,
[kSingulation] = ...,
...
};
I'm wondering if all of this stuff would be better suited for a class definition for encapsulation purposes. Or would I just use a factory method that receives a MapTileType and returns a RenderingStrategy?
I was thinking that I could also perhaps just use a delegate:
#protocol MapTileDelegate <NSObject>
-(NSString*)description;
-(void)renderBlahBlah...;
#end
Can somebody help break my analysis paralysis? :)
Without knowing more, there are two approaches that sound like they might make sense:
Turn the MapTileTypes into subclasses of MapTile that implement the custom behavior you're looking for.
Create a MapTileBehavior class or something along those lines and have instances of that class take the place of your MapTileTypes values.
i have helper C functions in some Objective C classes.
Just found out that the values of global, static C variables which i use in these functions are shared between instances of the class (duh), which is not what i want.
Is there a way to declare these variables local to instances of the class, so that they are visible by the helper functions without passing them explicitly?
Is there a way to declare these variables local to instances of the class
Sure, make them instance variables.
But:
so that they are visible by the helper functions without passing them explicitly?
You can pass the object into the function. If you have appropriate accessors, the function can get them. And if you have mutators, it can modify them, too.
But if you're doing that, you might as well just create a method, and automatically have access to the instance variables.
want to avoid method calls where necessary
logically separate it so your low level code is in c or c++, then add the required data to your objc class:
/* c example */
typedef struct t_generator {
UInt32 a;
} t_generator;
static void Generate(t_generator* const gen) {
/.../
}
#interface MONObjCGeneratorContainer : NSObject
{
t_generator generator;
NSString * name;
UInt32 b;
}
#end
if the data interface is as simple you can just access them from the instance:
- (void)method { GenerateB(&b); }
that should meet all the requirements you have posted (so far).
I have two methods -a and -b.
-a calls sometimes -b, and -b sometimes calls -a. Both methods are intended to be private, and not called from outside.
But I had to make one of them public in the .h file, because otherwise the compiler would go crazy and give a warning for either one of them.
Is there any valid and good-practise solution for that problem?
Traditionally, what you'd do is define a category (something like #interface MyClass (MyClass_Private) inside the implementation file that declares the private methods. Apple recently introduced a feature called a class extension that is intended for this exact case. It's basically a specialization of a category, but the class has to implement the methods when it's first defined. It looks like:
#interface MyObject ()
- (void)setNumber:(NSNumber *)newNumber;
#end
Implement a protocol.
or
Write a second header file with a category.
If you really want the functions to be private, you need to declare them as static. To eliminate the cyclic dependency, one should be declared before the other is defined. Here's a simple example:
static void b(); /* forward declaration */
static void a()
{
if (foo)
b(); /* forward-declared, so we're ok */
}
static void b()
{
if (bar)
a(); /* already defined, so we're ok */
}
This is all valid C, and so based on the OP's comment I assume this is valid ObjC as well.