Add object to array only if the object is not in already - objective-c

I want to add object to array only if the array already does not contain that object.
How to do opposite of containsObject method in NSArray ?

Use an NSMutableOrderedSet, whose addObject: method does exactly what you want:
Appends a given object to the mutable ordered set, if it is not already a member.

Here's how I'd do it:
if (![myArray containsObject:objectToAdd]){
[myArray addObject:objectToAdd];
}
More detail here:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSArray_Class/NSArray.html
Note that because the containsObject method queries every object in the array there are some performance considerations when using it on larger arrays.

if your object is of NSString* type you can do fast enumeration like this
BOOL found = NO;
for(NSString *object in YourArray)
{
if([object isEqualtoString:#"My text"])
{
found = YES;
}
}
if(!found)
{
//addObject
}
there are many isEqual methods in objective-c for different data types

Related

DFS algorithm implementation at Objective C

I am trying to implement the Objective C realization of this algorithm. Here the implementation of it:
#implementation DFSAlgorithm
-(void)dfs:(Graph*)g andStartingPosition:(int)s{
[self performDFS:g andPosition:s];
}
-(void)markedArrayInit:(int)capacity{
//0 is for unmarked vertices
//1 is form marked ones
self.marked=[[NSMutableArray alloc]initWithCapacity:capacity];
for(int i=0;i<[self.marked count];i++)
[self.marked replaceObjectAtIndex:i withObject:[NSNumber numberWithInt:0]];
}
-(void)performDFS:(Graph *)g andPosition:(int)v{
[self markedArrayInit:(int)[g numberOfVertices]];
[self.marked replaceObjectAtIndex:v withObject:[NSNumber numberWithInt:1]];
for (NSNumber *vertex in [g.vertices objectAtIndex:v]){
if(1==[self isMarked:v atGraph:g]){
NSLog(#"%d",(int)vertex);
[self performDFS:g andPosition:(int)vertex];
}
}
}
-(int)isMarked:(int)v atGraph:(Graph *)g{
return [self.marked objectAtIndex:v];
}
#end
However, I don't understand why the following error occurs:
[__NSArrayM replaceObjectAtIndex:withObject:]: index 0 beyond bounds for empty array'
How can I correctly initialize the marked array?
Thank you.
An NSMutableArray is created empty, the capacity value you pass is just a hint to the implementation about how large you expect the array to become.
Therefore replaceObjectAtIndex:withObject: does not work for you, as the array is empty you have no objects to replace.
Instead just use addObject: capacity times.
In your markedArrayInit method you create empty mutable array and reserve memory for it to hold at least capasity number of items. But you do not actually add anything to it (for loop in that method does not actually do anything at all). To fix your problem you can add enough number of items in for loop:
for (int i=0;i< initWithCapacity:capacity;i++)
[self.marked addObject: #0];
}
Edit:
Your implementation has several other problems:
you initialize marked array on each call to performDFS:andPosition:, and call that method recursively. You should move initialization to dfs:andStartingPosition: method
In isMarked:atGraph: method you return object from array, not the numeric value it holds - so it will never be 1, you might want to replace it with the following implementation (Note that method name implies we return some boolean value, not an integer that we'll need to interpret later):
-(BOOL)isMarked:(int)v atGraph:(Graph *)g {
return [self.marked[v] intValue] == 1;
}
...
if([self isMarked:v atGraph:g]){
...
}
There're better data structures to store indices of marked nodes, e.g. NSSet or NSIndexSet
You try to replace not existing object inside array. In markedArrayInit use addObject: method from NSMutableArray. [self.marked count] is always 0 in for cycle.

Obj-C: using mutable and returning non mutable classes in methods

In objective-C I find myself creating alot of Mutable objects and then returning them as non mutable objects. Is the way I am doing it here, simply returning the NSMutableSet as an NSSet a good practice? I was thinking maybe I should specify that i make a copy of it.
/** Returns all the names of the variables used in a given
* program. If non are used it returns nil */
+ (NSSet *)variablesUsedInProgram:(id)program
{
NSMutableSet* variablesUsed = [[NSMutableSet alloc]init];
if ([program isKindOfClass:[NSArray class]]) {
for (NSString *str in program)
{
if ([str isEqual:#"x"] || [str isEqual:#"y"] || [str isEqual:#"a"] || [str isEqual:#"b"])
[variablesUsed addObject:str];
}
}
if ([variablesUsed count] > 0) {
return variablesUsed;
} else {
return nil;
}
}
If I were you, I would do it this way.
+ (NSSet *)variablesUsedInProgram:(id)program
{
NSSet *variablesUsed;
if ([program isKindOfClass:[NSArray class]]) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF = 'x' or SELF = 'y' or SELF = 'z'"];
variablesUsed = [NSSet setWithArray:[program filteredArrayUsingPredicate:predicate]];
}
int count;
return (count = [variablesUsed count]) > 0 ? variablesUsed : nil;
}
I find using predicate to filter array quite comprehensive and easy. Rather than dealing with creating a new mutable type and then testing certain condition, adding until the loop; in this scenario, it seems to be easier to use predicate. Hope this helps you.
It depends how much safety you require. If you return the object as an NSSet it will still be an NSMutableSet, so it could easily be cast back to one and modified.
Certainly, if you're creating a public API, I'd recommend returning a copy. For in internal project, perhaps the method signature already makes the intention clear enough.
Its, worth noting that, generally the performance impact of returning a copy is negligible - copying an immutable instance is effectively free whereas each copy sent to a mutable-passing-as-immutable will create another copy. So I would say its good practice to default to.
No. This is an absolutely correct OOP approach (it takes advantage of polymorphism). Every NSMutableSet is a proper NSSet. Don't copy superfluously.
Not a full answer here, consider NSProxy's one, but I want to clarify something.
In your case you create your object from scratch, and you don't set any ivar to point to that object. In my opinion in a good percentage of cases you don't need to make a copy of the mutable object returned. But if there is a good reason to deny the class client from mutating the class, then you should copy the variable.
Consider a property like this:
#property (nonatomic,assign) NSSet* set;
The class client could do this:
NSMutableSet* set= ... ; // inizialized to some value
classInstance.set= set;
// Mutate the set
Once mutated the set it could make the class be in an inconsistent state.
That's why when I have a property with the type of a class that has also a mutable version, I always put copy instead of assign in the property.

Can I use NSPredicate for this?

Here's my loop:
- (NSArray *)myArray
{
if (!_myArray)
{
NSMutableArray *array = [NSMutableArray array];
for (MyReport *report in self.helper.myReportType.reports)
{
[array addObject:report.nameString];
}
_myArray = array;
}
return _myArray;
}
This works (with obviously some casting happening, which may not be great or desirable), but surely there's a better way to do this. Can NSPredicate help here? (I'm still new to using NSPredicate, but I believe it's primarily for filtering data, not building an array like this?) Otherwise, how can I rewrite this using another Apple helper class?
NSPredicate is more about filtering data, like you said. A clean way to do this is with Key-Value Coding, which when used on NSArray, calls the valueForKey: method on each of its objects, and returns the results as an NSArray:
_myArray = [self.helper.myReportType.reports valueForKey:#"nameString"];
Note that this method converts nil to NSNull automatically. More advanced KVC-Collection operator information can be found here: http://nshipster.com/kvc-collection-operators/
Use below code-
[self.helper.myReportType.reports valueForKey:#"nameString"];
It will return you array of nameString's from reports array.

sortedArrayUsingSelector what is it doing?

I am still new to objective-c and am trying to figure out what this statement is doing exactly.
[names allKeys] sortedArrayUsingSelector:#selector(compare:)];
I know that allKeys is getting all the keys from my dictionary. I know that sortedArrayUsingSelector is sorting my array im creating. Then im calling the compare method, that is where I am lost what is this doing? From the document on apple it says that "Returns an NSComparisonResult value that indicates whether the receiver is greater than, equal to, or less than a given number." I dont understand how it is sorting based of that method.
NSArray * sortedKeys = [[names allKeys] sortedArrayUsingSelector:#selector(compare:)];
The above code returns a sorted array of the dictionary keys using the selector you provide. The selector is actually the function that will be called on the object that is being sorted in your array. In this case your array contains strings so in the actual NSArray sorting code the following would be happening,
//...
[key1 compare:key2];
//..
If you passed in a different selector lets say #selector(randomFunction:) then in the sorting code the following would happen
//..
[key1 randomFunction:key2];
//..
Since NSString does not respond to the selector randomFunction you would get an error. If you wanted to create your own type of comparison function you would need to add a category to the class that the array contains (in your case a category to NSString).
A better way to sort an array is to use a block statement.
id mySort = ^(NSString * key1, NSString * key2){
return [key1 compare:key2];
};
NSArray * sortedKeys = [[names allKeys] sortedArrayUsingComparator:mySort];
The reason it's a better way is sorting any objects is very easy to do.
id mySort = ^(MyObject * obj1, MyObject * obj2){
return [obj1.title compare:obj2.title];
};
NSArray * sortedMyObjects = [myObjects sortedArrayUsingComparator:mySort];
- (NSComparisonResult)compare:
{
// if (value of firstObject) < (value of secondObject)
// return NSOrderedAscending
// else if (value of firstObject) == (value of secondObject)
// return NSOrderedSame
// else
// return NSOrderedDescending
}
The -sortedArrayUsingSelector: method in your example calls the -compare: method on the objects in the array. For some objects Apple has already implemented a -compare: method, for example if you read through the NSString documentation, you'll find a -compare: method implemented. You can also call custom comparison methods on your own custom objects if you've implemented a comparison method in these objects. Please note the comparison method doesn't have to be called -compare:, of importance is only the return value (NSComparisonResult) and the object the method receives.
The new array contains references to the receiving array’s elements, not copies of them.
The comparator message is sent to each object in the array and has as its single argument another object in the array.
For example, an array of NSString objects can be sorted by using the caseInsensitiveCompare: method declared in the NSString class. Assuming anArray exists, a sorted version of the array can be created in this way:
NSArray *sortedArray =
[anArray sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
You should probably be using caseInsensitiveCompare: in this situation since you are most likely ordering an array of strings (keys from a dictionary).
You've assumed that sortedArrayUsingSelector is somehow separate to the compare: part of the code. This is not the case. compare: is the selector that is used to sort the array.
The sorting method gives you back an array where each element, when sent the specified selector and the next element in the array, gives the correct sort order.
How NSArray achieves this is not public but at root, the selector you define is used to compare pairs of objects from within the array, the result of which informs their placement in the sorted array.

Getting an object from an NSSet

If you can't get an object with objectAtIndex: from an NSSet then how do you retrieve objects?
There are several use cases for a set. You could enumerate through (e.g. with enumerateObjectsUsingBlock or NSFastEnumeration), call containsObject to test for membership, use anyObject to get a member (not random), or convert it to an array (in no particular order) with allObjects.
A set is appropriate when you don't want duplicates, don't care about order, and want fast membership testing.
NSSet doesn't have a method objectAtIndex:
Try calling allObjects which returns an NSArray of all the objects.
it is possible to use filteredSetUsingPredicate if you have some kind of unique identifier to select the object you need.
First create the predicate (assuming your unique id in the object is called "identifier" and it is an NSString):
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:#"identifier == %#", identifier];
And then choose the object using the predicate:
NSObject *myChosenObject = [mySet filteredSetUsingPredicate:myPredicate].anyObject;
NSArray *myArray = [myNSSet allObjects];
MyObject *object = [myArray objectAtIndex:(NSUInteger *)]
replace NSUInteger with the index of your desired object.
For Swift3 & iOS10 :
//your current set
let mySet : NSSet
//targetted index
let index : Int
//get object in set at index
let object = mySet.allObjects[index]
NSSet uses the method isEqual: (which the objects you put into that set must override, in addition, the hash method) to determine if an object is inside of it.
So, for example if you have a data model that defines its uniqueness by an id value (say the property is:
#property NSUInteger objectID;
then you'd implement isEqual: as
- (BOOL)isEqual:(id)object
{
return (self.objectID == [object objectID]);
}
and you could implement hash:
- (NSUInteger)hash
{
return self.objectID; // to be honest, I just do what Apple tells me to here
// because I've forgotten how Sets are implemented under the hood
}
Then, you can get an object with that ID (as well as check for whether it's in the NSSet) with:
MyObject *testObject = [[MyObject alloc] init];
testObject.objectID = 5; // for example.
// I presume your object has more properties which you don't need to set here
// because it's objectID that defines uniqueness (see isEqual: above)
MyObject *existingObject = [mySet member: testObject];
// now you've either got it or existingObject is nil
But yeah, the only way to get something out of a NSSet is by considering that which defines its uniqueness in the first place.
I haven't tested what's faster, but I avoid using enumeration because that might be linear whereas using the member: method would be much faster. That's one of the reasons to prefer the use of NSSet instead of NSArray.
for (id currentElement in mySet)
{
// ** some actions with currentElement
}
Most of the time you don't care about getting one particular object from a set. You care about testing to see if a set contains an object. That's what sets are good for. When you want to see if an object is in a collection sets are much faster than arrays.
If you don't care about which object you get, use -anyObject which just gives you one object from the set, like putting your hand in a bag and grabbing something.
Dog *aDog = [dogs anyObject]; // dogs is an NSSet of Dog objects
If you care about what object you get, use -member which gives you back the object, or nil if it's not in the set. You need to already have the object before you call it.
Dog *spot = [Dog dogWithName:#"Spot"];
// ...
Dog *aDog = [dogs member:spot]; // Returns the same object as above
Here's some code you can run in Xcode to understand more
NSString *one = #"One";
NSString *two = #"Two";
NSString *three = #"Three";
NSSet *set = [NSSet setWithObjects:one, two, three, nil];
// Can't use Objective-C literals to create a set.
// Incompatible pointer types initializing 'NSSet *' with an expression of type 'NSArray *'
// NSSet *set = #[one, two, three];
NSLog(#"Set: %#", set);
// Prints looking just like an array but is actually not in any order
//Set: {(
// One,
// Two,
// Three
// )}
// Get a random object
NSString *random = [set anyObject];
NSLog(#"Random: %#", random); // Random: One
// Iterate through objects. Again, although it prints in order, the order is a lie
for (NSString *aString in set) {
NSLog(#"A String: %#", aString);
}
// Get an array from the set
NSArray *array = [set allObjects];
NSLog(#"Array: %#", array);
// Check for an object
if ([set containsObject:two]) {
NSLog(#"Set contains two");
}
// Check whether a set contains an object and return that object if it does (nil if not)
NSString *aTwo = [set member:two];
if (aTwo) {
NSLog(#"Set contains: %#", aTwo);
}