1

I am struggling to find a shorthand version of the code shown below. Basically I am saving Events into core data. Each event has up to 15 contacts. newEvent is from an Event class.

The code below works great, but I don't want to have it duplicated 15 times for each contact. Is there an easier way?

if ([[selectedContacts objectAtIndex:14] objectAtIndex:0] != (id)[NSNull null]) {
    newEvent.contact15 = [[selectedContacts objectAtIndex:14] objectAtIndex:0];
}
else {
    newEvent.contact15 = @"";
}
1
  • 2
    Short answer: declare the contactX fields to be a single array and loop through it. Commented Jul 9, 2012 at 11:34

2 Answers 2

4

You can use this code

-(void) Solve{
    for (int i = 0 ; i < 15 ; i++){
        Contact *con = [newEvent.contacts objectAtIndex:14 - i];
        if ([[selectedContacts objectAtIndex:14 - i] objectAtIndex:0] != (id)[NSNull null]) {
            con = [[selectedContacts objectAtIndex:14 - i] objectAtIndex:0];
        }
        else {
            con = @"";
        }
    }
}

just you should define contact in your newEvent class as Array

Sign up to request clarification or add additional context in comments.

1 Comment

I am not sure how to save an array in core data. But this answer looks great, cheers for the help though :)
0

You could use NSSelectorFromString to translate [NSString stringWithFormat:@"setContact%d", 15] to SEL value and then using performSelector. But ARC won't like that.

You can #define a C macro with this statement, then call it 15 times and immediately #undef it. It will be much shorter, though not pretty.

But the best would be to redesign the class to have single contacts array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.