This one took me forever, and I still don’t really understand it. None of the random examples in other posts worked for me. Either they didn’t work, or they created incompatible conversions, and again the documentation didn’t help me out at all.
I also had trouble understanding how the arrays were saved, I kept getting errors that said I couldn’t use the asset array. Eventually I came up with the following code that, with the exception of the random number generator not being really random, I think is a pretty simple solution. It totals the number of assets that an employee has and removes the last one added (since I can’t generate a random number between 0 and totalAssets).
[code]-(void)removeAsset:(BNRAsset *)a
{
//Is assets nil?
if (_assets){
[_assets removeObject: a];
}
}
[/code]
------ and in main
[code]//Create 10 assests
for (int i = 0; i <10; i++){
//Create an asset
BNRAsset *asset = [[BNRAsset alloc] init];
//Give it an interesting lable
NSString *currentLabel = [NSString stringWithFormat:@"Laptop %d", i];
asset.label = currentLabel;
asset.resaleValue = 350 + i * 17;
//Get a random number between 0 and 9 inclusive
NSUInteger randomIndex= random() % [employees count];
//Find that employee
BNREmployee *randomEmployee = [employees objectAtIndex:randomIndex];
//Assign the asset tothe employee
[randomEmployee addAsset:asset];
}
//Get a random number between 0 and 9 inclusive
NSUInteger randomIndex= random() % [employees count];
//Find that employee
BNREmployee *randomEmployee = [employees objectAtIndex:randomIndex];
NSUInteger assetNumber = random() % [randomEmployee.assets count];
BNRAsset *totalAssets = [randomEmployee.assets objectAtIndex:assetNumber ];
NSLog(@"Employees: %@", employees);
NSLog(@"I will remove Employee %@", randomEmployee);
[randomEmployee removeAsset:totalAssets];
NSLog(@"Removed Employee %@'s asset", randomEmployee);
NSLog(@"Now the total Employee's assets are: %@", employees);
[/code]
-------- the results
2015-04-24 18:36:42.396 BMITime[858:36930] Employees: (
"<Employee 0: $0 in assets>",
"<Employee 1: $503 in assets>",
"<Employee 2: $469 in assets>",
"<Employee 3: $768 in assets>",
"<Employee 4: $0 in assets>",
"<Employee 5: $836 in assets>",
"<Employee 6: $819 in assets>",
"<Employee 7: $384 in assets>",
"<Employee 8: $0 in assets>",
"<Employee 9: $486 in assets>"
)
2015-04-24 18:36:42.397 BMITime[858:36930] I will remove Employee <Employee 2: $469 in assets>
2015-04-24 18:36:42.397 BMITime[858:36930] Removed Employee <Employee 2: $0 in assets>'s asset
2015-04-24 18:36:42.398 BMITime[858:36930] Now the total Employee’s assets are: (
"<Employee 0: $0 in assets>",
"<Employee 1: $503 in assets>",
"<Employee 2: $0 in assets>",
"<Employee 3: $768 in assets>",
"<Employee 4: $0 in assets>",
"<Employee 5: $836 in assets>",
"<Employee 6: $819 in assets>",
"<Employee 7: $384 in assets>",
"<Employee 8: $0 in assets>",
"<Employee 9: $486 in assets>"
)