Skip to content

Commit

Permalink
Refuse to construct nil objects.
Browse files Browse the repository at this point in the history
  • Loading branch information
maleadt committed Mar 4, 2023
1 parent 91f3600 commit aac61bd
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
16 changes: 12 additions & 4 deletions src/syntax.jl
Original file line number Diff line number Diff line change
Expand Up @@ -195,17 +195,25 @@ macro objcwrapper(ex...)
struct $name <: $super
ptr::id

# restrict the default constructor
$name(ptr::id) = new(ptr)
# restrict the default constructor to object pointer types,
# and make sure we don't create nil objects
function $name(ptr::id)
ptr == nil && throw(UndefRefError())
new(ptr)
end
end
end
else
quote
mutable struct $name <: $super
ptr::id

# restrict the default constructor
$name(ptr::id) = new(ptr)
# restrict the default constructor to object pointer types,
# and make sure we don't create nil objects
function $name(ptr::id)
ptr == nil && throw(UndefRefError())
new(ptr)
end
end
end
end
Expand Down
5 changes: 5 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,17 @@ using ObjectiveC
end

# smoke test
@objcwrapper TestNSString <: Object
let data = "test"
ptr = @objc [NSString stringWithUTF8String:data::Ptr{UInt8}]::id
@test ptr isa id
@test class(ptr) isa Class
@test "length" in methods(ptr)
@test 4 == @objc [ptr::id length]::Culong

obj = TestNSString(ptr)
@test Base.unsafe_convert(id, obj) == ptr
@test_throws UndefRefError TestNSString(nil)
end

@testset "foundation" begin
Expand Down

0 comments on commit aac61bd

Please sign in to comment.