Skip to content

Commit e3bd2e0

Browse files
committed
Update NSString example usage
1 parent 42bd737 commit e3bd2e0

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

objc2-foundation/examples/basic_usage.rs

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use objc2::rc::autoreleasepool;
2-
use objc2_foundation::{NSArray, NSCopying, NSDictionary, NSObject, NSString};
2+
use objc2_foundation::{ns_string, NSArray, NSDictionary, NSObject};
33

44
fn main() {
55
// Create and compare NSObjects
@@ -24,19 +24,20 @@ fn main() {
2424
let mut objs = NSArray::into_vec(array);
2525
let obj = objs.pop().unwrap();
2626

27-
// Create an NSString from a str slice
28-
let string = NSString::from_str("Hello, world!");
27+
// Create a static NSString
28+
let string = ns_string!("Hello, world!");
2929
// Use an autoreleasepool to get the `str` contents of the NSString
3030
autoreleasepool(|pool| {
3131
println!("{}", string.as_str(pool));
32-
let string2 = string.copy();
33-
println!("{}", string2.as_str(pool));
3432
});
33+
// Or simply use the `Display` implementation
34+
let _s = string.to_string(); // Using ToString
35+
println!("{}", string); // Or Display directly
3536

3637
// Create a dictionary mapping strings to objects
37-
let keys = &[&*string];
38+
let keys = &[string];
3839
let vals = vec![obj];
3940
let dict = NSDictionary::from_keys_and_objects(keys, vals);
40-
println!("{:?}", dict.get(&string));
41+
println!("{:?}", dict.get(string));
4142
println!("{}", dict.len());
4243
}

objc2-foundation/src/string.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,13 @@ const UTF8_ENCODING: i32 = 4;
3030
const NSNotFound: ffi::NSInteger = ffi::NSIntegerMax;
3131

3232
extern_class! {
33-
/// A static, plain-text Unicode string object.
33+
/// An immutable, plain-text Unicode string object.
34+
///
35+
/// Can be created statically using the [`ns_string!`] macro.
3436
///
3537
/// See [Apple's documentation](https://developer.apple.com/documentation/foundation/nsstring?language=objc).
38+
///
39+
/// [`ns_string!`]: crate::ns_string
3640
#[derive(PartialEq, Eq, Hash)]
3741
unsafe pub struct NSString: NSObject;
3842
// TODO: Use isEqualToString: for comparison (instead of just isEqual:)
@@ -173,6 +177,10 @@ impl NSString {
173177
// TODO: Allow usecases where the NUL byte from `UTF8String` is kept?
174178

175179
/// Creates an immutable `NSString` by copying the given string slice.
180+
///
181+
/// Prefer using the [`ns_string!`] macro when possible.
182+
///
183+
/// [`ns_string!`]: crate::ns_string
176184
#[doc(alias = "initWithBytes")]
177185
#[doc(alias = "initWithBytes:length:encoding:")]
178186
#[allow(clippy::should_implement_trait)] // Not really sure of a better name

0 commit comments

Comments
 (0)