Ad space (banner)
๐ŸŽObjective-C Lessons
Lesson 27 / 68

Handling sets (data without duplicates) with NSSet

This lesson covers handling data without duplicates using NSSet in Objective-C, with the aim of understanding the set as a data structure.

NSSet is a box that cannot hold the same value twice. It is handy for removing duplicates from an array and for checking membership quickly.

The sample code builds a set from the duplicate-laden array @[@1, @2, @2, @3, @3, @3] with [NSSet setWithArray:nums], and the duplicates disappear automatically. Note containsObject: checking whether a value is present.

A common early stumble is that an NSSet's ordering is not guaranteed. It will not necessarily be in insertion order as an array is, so where order matters an array suits better.

In professional work, a Set's containsObject: also outruns an array's when there is a lot of data, which makes it very convenient for deduplication.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Objective-C directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)