First off, I agree that this is so far easily the most confusing chapter and challenge in the book. I think part of this is due to how complicate these concepts and their implementations are in Objective C and how weird some of the syntax is (Obj-C is my first language, but surely others must be more internally consistent), but I think it’s also because the Authors just throw huge amounts of concepts and code at the reader with a fairly small amount of explanation to go with it.
That being said…
My solution is very similar to that by ibex10. The program often gives more than one asset to an employee, so presumably we’re trying to remove a specific one, not everything the employee has.
I did this by iterating through all the employees/assets and looking at each asset’s NSString label, to see if it matches the one we’re trying to delete.
Here’s my function in employee.m (obviously with a matching bit in employee.h)
- (void)removeAssetWithLabel:(NSString *)a
{
BOOL wasFound = NO;
int assetCounter = 0; //employees have their assets in an array so we have to start as 0, then 1, etc.
for (BNRAsset *testAsset in _assets) {
NSLog(@"testing %@ vs %@", testAsset.label, a); //This is unnecessary, but is a much quicker way to see what's going on than putting a breakpoint and iterating step by step
if ([a isEqualToString:testAsset.label]) { //testing the string that the function was called with VS the label of the object currently being checked
[_assets removeObjectAtIndex:assetCounter];
wasFound = YES;
NSLog(@"The asset <%@> was deleted", a);
}
assetCounter++;
}
if( wasFound == NO ){
NSLog(@"This employee doesn't %@. Moving on.", a);
}
}
Then in main.m I added this:
NSLog(@"Trying to delete laptop 7...");
for (BNREmployee *e in employees) {
[e removeAssetWithLabel:@"Laptop 7"];
}
The next bit doesn’t do anything except send out some NSLogs, but it helped me to understand how the program works.
In employee.m…
- (void)listAssets
{
for(BNRAsset *testAsset in _assets) {
NSLog(@"Employee %i has %@", self.employeeID, testAsset.label);
}
}
in main.m…
for (BNREmployee *e in employees) {
[e listAssets];
}