-1

Is it possible to create dynamically instances of a class giving them specific names (e.g. Friend1, Friend2, etc)?

I have a "Friends" class with some instance variables (e.g. Name and Surname). In my app user selects from a list the number of "Friends" he wants to add. So in case he selects 5 the UITableView will be populated with 10 empty fields (Name and Surname).

Do you know any way to create these objects "on the fly"?

jscs
  • 63,694
  • 13
  • 151
  • 195
V. Pier
  • 1
  • 2

2 Answers2

0

When he selects 5, create an array of friends:

friends = [[NSMutableArray alloc] init];
for (int i = 0; i < 5; i++)
    [friends addObject:[[[Friend alloc] init] autorelease]];
[tableView reload];

(where friends NSMutableArray is declared in interface section of your view controller)

And in UITableViewDataSource:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == friendsSection)
        return [friends count] * 2;
    else ...;
}

I leave -tableView:cellForRowAtIndexPath: implementation as an exercise to the reader, it depends on too many details you didn't describe.

  • My example does not utilize proper resource management and probably other details are missing, of course. –  May 06 '13 at 18:36
  • I thought that I needed to know the names of the objects in order to store user input. – V. Pier May 06 '13 at 18:37
  • You may treat `friends[n]` as a name of object, if you want think that way. –  May 06 '13 at 18:39
0

Well, your problem is solved, good! But your question addressed also a problem that is not yet solved: "to create dynamically instances of a class giving them specific names", so that you can refer to them later using these names.
Referring to an object essentially means to send it a message. In the Objective-C runtime, this is done using objc_msgSend(id theReceiver, SEL theSelector, ...). Thus you need a pointer to theReceiver. I interpret you question so as "is it possible to associate the pointer to a new instance with a dynamically created name. I think this is possible using a dictionary like so:
You create dynamically your identifier: NSString *myIdentifier = @"anyString"; or any other way to create a string. Then you create an instance of your class: MyClass *myObject = [[MyClass alloc] init]; or any other way to instantiate it. Eventually you establish the association: NSDictionary *dict = @{myIdentifier: myObject};
Later you can send the object a message, using the object's name as [[dict objectForKey:myIdentifier] message];
Maybe there is an easier way to do it...

Reinhard Männer
  • 14,022
  • 5
  • 54
  • 116